String
type has generally lots of choices for the values, so it prones to bugs.String
s as parameters of functions.https://doc.rust-lang.org/book/ch19-03-advanced-traits.html
use std::ops::Add;
struct Millimeters(u32);
struct Meters(u32);
impl Add<Meters> for Millimeters {
type Output = Millimeters;
fn add(self, other: Meters) -> Millimeters {
Millimeters(self.0 + (other.0 * 1000))
}
}
If we wrote a function with a parameter of type Millimeters
, we couldn’t compile a program that accidentally tried to call that function with a value of type Meters
or a plain u32
.
Newtypes are a zero-cost abstraction - there is no runtime overhead.