Rust

From / Into Conversions

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Implement `From` and you get `Into` for free. Then `.into()` and `T::from(x)` both work. The single most idiomatic way to express type conversions in Rust.
Rust
Raw
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 main() {
    let boiling = Celsius(100.0);
    let f: Fahrenheit = boiling.into();          // uses From impl above
    println!("{} °F", f.0);                      // 212 °F

    // Or call From directly
    let body = Fahrenheit::from(Celsius(37.0));
    println!("{:.1} °F", body.0);                // 98.6 °F

    // From is also why ? upcasts errors — every Error type into Box<dyn Error>
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.