Skip to content

New derives: From and Deref #2026

Description

@iitalics

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions