It's often useful to wrap a single type into a new one, to be able to add new methods, provide more documentation and possibly type safety.
For example,
pub struct Inches(f32);
pub struct Meters(f32);
This way if the units are used incorrectly we get a type error. Fortunately there is no space overhead as well. This is very similar to newtype in Haskell.
I'm proposing that we consider being able to derive From and possibly Deref for structs with exactly one field. For the above example, adding #[derive(From, Deref)] above Inches would generate the code:
impl From<f32> for Inches {
fn from(x: f32) -> Self {
Inches(x)
}
}
impl Deref for Inches {
type Target = f32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
These or similar derives would significantly reduce boilerplate when creating wrapper types, thus encouraging their use.
EDIT: fixed i32 => f32
It's often useful to wrap a single type into a new one, to be able to add new methods, provide more documentation and possibly type safety.
For example,
This way if the units are used incorrectly we get a type error. Fortunately there is no space overhead as well. This is very similar to
newtypein Haskell.I'm proposing that we consider being able to derive
Fromand possiblyDereffor structs with exactly one field. For the above example, adding#[derive(From, Deref)]aboveIncheswould generate the code:These or similar derives would significantly reduce boilerplate when creating wrapper types, thus encouraging their use.
EDIT: fixed i32 => f32