In Rust, the newtype idiom wraps an underlying types with another type to enforce correct usage. E.g.

struct Years(i64);
struct Days(i64);
 
impl Days {
    /// truncates partial years
    pub fn to_years(&self) -> Years {
        Years(self.0 / 365)
    }
}

The newtype idiom can also be a useful way to circumvent the orphan rule.

Conversions

see: Rust conversions

We can implement From or TryFrom to convert from primitives to newtype. And AsRef is useful to implement for code to consume new types as primitives.

See Also