[−][src]Macro new_type::newtype
Implements its arguments as newtypes.
The macro is meant to provide easy means to enhance the semantics of language built-ins. Newtypes come with Deref, DerefMut, AsRef, AsMut, and From traits. Further they implement almost all std::ops and std::cmp of the type they wrap. Exceptions are std::ops::{Drop, Fn, FnMut, FnOnce, Index, IndexMut, RangeBounds}.
Examples
Operations are available on newtypes:
newtype!(Count); let count_one = Count(100); let count_two = Count(50); // We can add 'Count' because we can add i32! assert_eq!(count_one + count_two, Count(150))
Functions are available on newtypes:
newtype!(Humans); let mut some_humans = Humans(HashSet::new()); some_humans.insert("Maria"); some_humans.insert("Peter"); let mut set = HashSet::new(); set.insert("Kim"); set.insert("Mia"); // We can extend Humans with a HashSet! some_humans.extend(set.iter()); // We can ask for '.len()' on Humans because we can ask for '.len()' on HashSet! assert_eq!(some_humans.len(), 4)
Newtypes can be nested:
newtype!(A, B, C); let abc_one = A(B(C(5))); let abc_two = A(B(C(5))); // We can add nested newtypes because we can add the wrapped type! assert_eq!(abc_one + abc_two, A(B(C(10))))