RRust By Example
intermediateTraits

From and Into

Type conversions with From and Into traits.

From and Into

Type conversions with From and Into traits.

Difficulty

Intermediate

Code

rust
#[derive(Debug)]
struct Celsius(f64);

#[derive(Debug)]
struct Fahrenheit(f64);

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

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

fn main() {
    let boiling = Celsius(100.0);
    let f: Fahrenheit = boiling.into();
    println!("{:?} = {:?}", Celsius(100.0), f);

    let f = Fahrenheit(72.0);
    let c: Celsius = f.into();
    println!("{:?} = {:?}", Fahrenheit(72.0), c);
}

Explanation

From/Into traits enable type conversions.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the traits category to build a complete understanding of this topic.

More Traits Examples