rust-lang / rust-lang/rfcs

New derives: From and Deref

Open
#2,026 19 comments 25 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang T-libs
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the issue's single-field Rust struct examples and the proposed From and Deref implementations, then review the repository's RFC process before determining the design scope. Done means resolving whether these derives should be specified and accepted as an RFC, including their intended behavior and constraints.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.