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>
}
Create a free account and build your private vault. Share publicly whenever you want.