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.
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.
HashMap
. Each key is a String
, and each value is a tuple of 3 different values.Mutex
and Arc
, we can leave those in the definition here as they are just for multithreading support, not the actual data.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
In developing Rust programs, using the command "cargo clippy" is essential. This tells us if our program is collection of likely bugs or not.
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)>>>>,
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.