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)
Syntax
impl From<T> for U { fn from(value: T) -> U } let u: U = t.into();
Parameters
| Parameter | Description |
|---|---|
From<T> |
Infallible conversion into Self. |
into() |
The reverse direction, inferred from the target type. |
TryFrom / try_into |
Conversions that can fail. |
Examples
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.
#[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.
Related
The ? operator· Propagate errors from functions returning Result or Option: unwrap Ok values and return early on Err.impl Display· Implement std::fmt::Display to control how a type prints with {} and converts with to_string().- Rust Traits · tutorial