Home
Rust
type Keyword Use
This page was last reviewed on Nov 20, 2024.
Dot Net Perls
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.
HashMap
Mutex
Arc
Part 1 We use a type alias for the HashMap. Each key is a String, and each value is a tuple of 3 different values.
Tuple
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 20, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.