Derive Macro derive_constructors::TryFrom

source ·
#[derive(TryFrom)]
{
    // Attributes available to this derive:
    #[no_from]
    #[enum_error_meta]
}
Expand description

It derives TryFrom trait where a tuple of this struct’s fields are passed to the [TryFrom::try_from] function, for example

#[derive(derive_constructors_proc::TryFrom, PartialEq, Debug)]
#[enum_error_meta(#[derive(Debug, PartialEq)])]
struct CharacterInfo{
    name: String,
    age: u8,
    #[no_from]
    times_appeared: u8,
    #[no_from(4)]
    years_studied: u8
}

let character_using_try_from = CharacterInfo::try_from(("Jorge", 23_u16)).unwrap();
let expected_character = CharacterInfo { name: "Jorge".to_string(), age: 23, times_appeared: 0, years_studied: 4};
assert_eq!(character_using_try_from, expected_character);

let produced_error = u8::try_from(23000_u16).unwrap_err();
let forced_error_using_try_from = CharacterInfo::try_from(("Jorge", 23000_u16)).unwrap_err();
let expected_error_on_try_from = CharacterInfoTryFromError::AgeError(produced_error);
assert_eq!(forced_error_using_try_from, expected_error_on_try_from);