Newtype in Rust
Overview
In Rust, the newtype pattern is a powerful tool used to create a distinct type by wrapping an existing type. This pattern is particularly useful for enhancing type safety and improving code readability. By leveraging the type system, newtypes help prevent bugs, such as parameter mix-ups, and provide more meaningful type names in public APIs. This approach ensures that the compiler can catch errors when arguments are accidentally switched, as the types will not match.
Example: FirstName Newtype
Consider the FirstName newtype, which wraps a String to represent a person's first name. This newtype not only provides a more descriptive type but also enforces constraints, such as a minimum length for the name.
Listing 2.7 The FirstName newtype
struct FirstName {
value: String,
}
impl FirstName {
pub fn new(name: &str) -> Result<FirstName, String> {
if name.len() < 2 {
Err("Name should be at least two characters".to_string())
} else {
Ok(FirstName {
value: name.to_string(),
})
}
}
pub fn get_value(&self) -> &String {
&self.value
}
}
// code for the other three newtypes
fn calculate_raise(first_name: FirstName, #1
_last_name: LastName,
_age: Age,
current_pay: Pay) -> Pay {
// ...
}
#1 Usage example: passes in the newtypes instead of the built-in types. If you accidentally switch arguments one and two or three and four, the compiler will throw an error.
In this example, the FirstName struct has a constructor method new that ensures the name is at least two characters long. Additionally, a get_value method is provided to safely access the inner String value.
Reducing Boilerplate with Macros
While the newtype pattern is beneficial, it can lead to verbose code. For instance, creating a single newtype like FirstName requires additional lines of code for the struct and its methods. To address this, Rust macros can be used to reduce boilerplate.
Listing 2.8 A macro for the newtype get_value method
struct FirstName {
value: String,
}
struct LastName {
value: String,
}
macro_rules! generate_get_value {
($struct_type:ident) => { #1
impl $struct_type { #2
pub fn get_value(&self) -> &String {
&self.value
}
}
}
}
generate_get_value!(FirstName); #3
generate_get_value!(LastName);
#1 We want one input argument, an identifier.
#2 We use that argument to implement a get_value method for the given struct.
#3 Now our FirstName and LastName structs will get the new method implemented for them.
In this macro, generate_get_value, we define a single matcher-transcriber pair. The macro takes an identifier as input, which is the name of the struct, and implements a get_value method for it. This approach allows us to easily add the get_value method to multiple structs, such as FirstName and LastName, without duplicating code. The flexibility of having multiple impl blocks for a struct ensures that users can still implement their own methods alongside those generated by the macro.
FAQ (Frequently asked questions)
What are newtypes in Rust?
Why are newtypes used in Rust?
How is a newtype implemented in Rust?
What is an example of a newtype in Rust?