Rust 1.99 (2024 edition) reference · Traits and Smart Pointers

Rust From and Into Type

Convert between types: implement From<T> and get Into for free; ? uses From to convert error types.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

impl From<T> for U { fn from(value: T) -> U }   let u: U = t.into();

Parameters

ParameterDescription
From<T> Infallible conversion into Self.
into() The reverse direction, inferred from the target type.
TryFrom / try_into Conversions that can fail.

Examples

Example 1
struct Celsius(f64);
struct Fahrenheit(f64);

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

fn main() {
    let c: Celsius = Fahrenheit(212.0).into();
    println!("{:.1}", c.0);
    let small: Result<u8, _> = u8::try_from(300_u32);
    println!("{small:?}");
}

Output

100.0
Err(TryFromIntError(PosOverflow))

Run this on your computer — see “Get Started” for setup.

From powers the ? operator
#[derive(Debug)]
enum AppError { BadNumber(std::num::ParseIntError) }

impl From<std::num::ParseIntError> for AppError {
    fn from(e: std::num::ParseIntError) -> Self { AppError::BadNumber(e) }
}

fn load(s: &str) -> Result<i32, AppError> {
    Ok(s.parse::<i32>()? * 2)   // ? converts ParseIntError into AppError
}

fn main() {
    println!("{:?}", load("42"));
    println!("{:?}", load("x"));
}

Output

Ok(84)
Err(BadNumber(ParseIntError { kind: InvalidDigit }))

Run this on your computer — see “Get Started” for setup.

Was this page helpful?