How to implement TryFrom and TryInto

Implement TryFrom to define safe conversions with error handling, while TryInto is automatically provided by the compiler.

Implement TryFrom for your target type and TryInto is automatically provided by the standard library. Define the type Error associated type and implement the try_from method to return Ok on success or Err on failure.

use std::convert::TryFrom;

struct PositiveInt(u32);

impl TryFrom<i32> for PositiveInt {
    type Error = &'static str;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value > 0 {
            Ok(PositiveInt(value as u32))
        } else {
            Err("Value must be positive")
        }
    }
}

// TryInto is automatically implemented for PositiveInt
let result: Result<PositiveInt, _> = 5.try_into();