How to Use std

:convert (From, Into, TryFrom, TryInto)

Implement From and Into for safe conversions, and TryFrom and TryInto for fallible conversions in Rust.

Use From and Into for infallible conversions, and TryFrom and TryInto for conversions that might fail. Implement From for the source type to define the conversion logic, then use Into automatically via the blanket implementation.

use std::convert::{From, Into, TryFrom, TryInto};

struct MyStruct { value: i32 }

impl From<i32> for MyStruct {
    fn from(val: i32) -> Self {
        MyStruct { value: val }
    }
}

impl TryFrom<u8> for MyStruct {
    type Error = &'static str;
    fn try_from(val: u8) -> Result<Self, Self::Error> {
        if val > 100 {
            Err("Value too large")
        } else {
            Ok(MyStruct { value: val as i32 })
        }
    }
}

fn main() {
    let s: MyStruct = 5.into();
    let s2: Result<MyStruct, _> = 50u8.try_into();
}