From and Into for type conversions

Marcus Chen Jan 2026
1 tab
struct UserId(u32);

impl From<u32> for UserId {
    fn from(id: u32) -> Self {
        UserId(id)
    }
}

fn main() {
    let id: UserId = 42.into();
    println!("User ID: {}", id.0);
}
1 file · rust Explain with highlit

The From and Into traits provide a standard way to convert between types. Implementing From<T> for your type automatically provides Into<T> via a blanket implementation. I use From for infallible conversions (like String::from("hello")) and TryFrom for fallible ones. This is more idiomatic than custom to_* methods. The ? operator works with From for error conversion: if your error type implements From<OtherError>, you can use ? on functions returning OtherError. I implement From for wrapping types (newtype pattern) and converting between representations. The trait makes APIs composable and consistent with standard library types.