TryFrom and TryInto

类似于 FromIntoTryFromTryInto 是 类型转换的通用 trait。不同于 From/Into 的是,TryFromTryInto trait 用于易出错的转换,也正因如此,其返回值是 Result 型。

  1. use std::convert::TryFrom;
  2. use std::convert::TryInto;
  3. #[derive(Debug, PartialEq)]
  4. struct EvenNumber(i32);
  5. impl TryFrom<i32> for EvenNumber {
  6. type Error = ();
  7. fn try_from(value: i32) -> Result<Self, Self::Error> {
  8. if value % 2 == 0 {
  9. Ok(EvenNumber(value))
  10. } else {
  11. Err(())
  12. }
  13. }
  14. }
  15. fn main() {
  16. // TryFrom
  17. assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
  18. assert_eq!(EvenNumber::try_from(5), Err(()));
  19. // TryInto
  20. let result: Result<EvenNumber, ()> = 8i32.try_into();
  21. assert_eq!(result, Ok(EvenNumber(8)));
  22. let result: Result<EvenNumber, ()> = 5i32.try_into();
  23. assert_eq!(result, Err(()));
  24. }