Type. Often in Rust programs, types can become complex—this is particularly problematic in multithreaded programs with Mutex and Arc. To keep code more readable, we can use type aliases.
With the type keyword, we alias an identifier to an actual Rust type. This means we can use the simple and short alias in place of the more complex real type.
Example. Suppose we have a HashMap we want to create on threads in a Rust program. The HashMap needs to be inside a Mutex. The Arc makes it faster to copy the data.
Part 2 For the Mutex and Arc, we can leave those in the definition here as they are just for multithreading support, not the actual data.
Part 3 Using a type alias does not affect the usage of the field at all—the code does not reference InnerHashMap here.
use std::collections::*;
use std::sync::*;
// Part 1: use type alias to represent the HashMap and its key and value types.
type InnerHashMap = HashMap<String, Vec<(usize, String, bool)>>;
struct Test {
// Part 2: use the type alias to simplify the long, complex type in a struct.
hash: Mutex<Arc<InnerHashMap>>,
}
fn main() {
// Part 3: create the struct and use it.
let test = Test {
hash: Mutex::new(HashMap::new().into()),
};
println!("Length: {}", test.hash.lock().unwrap().len());
}Length: 0
Clippy. In developing Rust programs, using the command "cargo clippy" is essential. This tells us if our program is collection of likely bugs or not.
Info Clippy will warn on complex types, and using a type alias (like InnerHashMap) will resolve the warning.
warning: very complex type used. Consider factoring parts into `type` definitions
--> src/main.rs:9:11
|
9 | hash: Mutex<Arc<HashMap<String, Vec<(usize, String, bool)>>>>,
Summary. A key advantage of Rust is that Rust programs often are of high quality. With type aliases, we resolve a Clippy lint which helps us maintain code quality levels.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.