Sub topic 10
From: defining a conversion
This chapter assumes you know structs, enums, impl Trait for Type, and basic Result handling. It covers how to define a conversion with From. The next chapters cover Into and the ? operator in detail.
What From is
From is a standard library trait that says "a value of type T can be turned into Self, and the conversion cannot fail." Its definition is short:
pub trait From<T>: Sized {
fn from(value: T) -> Self;
}You implement From<T> on the type you want to produce. The type in the angle brackets is the input. The type in impl ... for is the output.
A worked example
This program converts a temperature in Celsius into Fahrenheit.
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::from(boiling);
println!("{}", f.0);
}It prints 212. Read the impl as "Fahrenheit can be made from Celsius". The call Fahrenheit::from(boiling) names the output type first, which keeps the direction clear.
The function takes c by value, so boiling is moved and cannot be used afterwards. If you want to convert from a borrowed value, implement From<&Celsius> as a separate impl.
Rules that shape how you write From
- The conversion must not fail. If it can fail, use
TryFrom, covered later in this tutorial. - The conversion should not lose information in surprising ways.
From<u8> for u32is fine. A conversion that silently truncates is not. - You can implement
Fromseveral times for one type, once per input type. Each impl is a separate trait, such asFrom<Celsius>andFrom<f64>. - The standard library already has many impls.
String::from("text")andi64::from(5_i32)both use this trait.
Several inputs for one type
A type can accept different sources by implementing From more than once.
#[derive(Debug)]
struct UserId(u64);
impl From<u64> for UserId {
fn from(n: u64) -> Self {
UserId(n)
}
}
impl From<u32> for UserId {
fn from(n: u32) -> Self {
UserId(u64::from(n))
}
}
fn main() {
println!("{:?}", UserId::from(7_u64));
println!("{:?}", UserId::from(7_u32));
}The compiler picks the impl from the type of the argument. With a bare literal such as UserId::from(7), it may be unable to choose, so give the literal a suffix or a typed variable.
Common errors
- Implementing the wrong direction. Writing
impl From<Fahrenheit> for Celsiuswhen you need the reverse produces a type mismatch at the call site. Check which type appears afterfor. - Panicking inside
from. Callingunwrap()or indexing in aFromimpl hides a failure behind a signature that promises success. Switch toTryFrom. - Conflicting impls. You cannot write
From<T> for T, because the standard library already provides it for every type. - Orphan rule violations. You can implement
Fromonly if your crate defines either the input type or the output type.impl From<String> for Vec<u8>in your own crate is rejected, because you define neither type.
Exercise
You have struct Meters(f64); and struct Feet(f64);. Write the impl that lets you call Meters::from(Feet(10.0)). One foot is 0.3048 meters.
Show answer
impl From<Feet> for Meters { fn from(f: Feet) -> Self { Meters(f.0 * 0.3048) } }. The output type, Meters, goes after for, and the input type, Feet, goes inside From<...>.