typestar

From and Into in Rust

Implement From and you get Into for free, in both directions of the call.

struct Celsius(f64);
struct Fahrenheit(f64);

impl From<Celsius> for Fahrenheit {
    fn from(c: Celsius) -> Self {
        Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
    }
}

fn report(temp: impl Into<Fahrenheit>) -> String {
    format!("{:.1}F", temp.into().0)
}

fn main() {
    let f = Fahrenheit::from(Celsius(100.0));
    println!("{:.1}", f.0);

    let also: Fahrenheit = Celsius(0.0).into();
    println!("{:.1}", also.0);
    println!("{}", report(Celsius(21.5)));
}

How it works

  1. From converts an owned value into your type.
  2. .into() is the same conversion, chosen by the target type.
  3. Generic functions take impl Into<T> to accept both.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
429
Tokens
143
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 1 of 4 in Standard traits, step 8 of 19 in Traits & generics.

← Previous Next →