TryFrom and TryInto
Similar to From and Into, TryFrom and TryInto are
generic traits for converting between types. Unlike From/Into, the
TryFrom/TryInto traits are used for fallible conversions, and as such,
return Results.
1. use std::convert::TryFrom;
2. use std::convert::TryInto;
4. #[derive(Debug, PartialEq)]
5. struct EvenNumber(i32);
7. impl TryFrom<i32> for EvenNumber {
8. type Error = ();
10. fn try_from(value: i32) -> Result<Self, Self::Error> {
11. if value % 2 == 0 {
12. Ok(EvenNumber(value))
13. } else {
14. Err(())
15. }
16. }
17. }
19. fn main() {
20. // TryFrom
22. assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
23. assert_eq!(EvenNumber::try_from(5), Err(()));
25. // TryInto
27. let result: Result<EvenNumber, ()> = 8i32.try_into();
28. assert_eq!(result, Ok(EvenNumber(8)));
29. let result: Result<EvenNumber, ()> = 5i32.try_into();
30. assert_eq!(result, Err(()));
31. }
