TryFrom 和 TryInto

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将探索 Rust 中 TryFromTryInto 的用法,它们是用于在类型之间进行可能失败的转换并返回 Result 类型的通用 trait。我们提供了一个示例代码片段,展示了如何实现 TryFrom 以将 i32 转换为自定义的 EvenNumber 结构体,然后展示如何使用 TryFromTryInto 来执行转换并处理可能的错误。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,并通过 rustc main.rs &&./main 进行编译和运行。

TryFromTryInto

FromInto 类似,[TryFrom] 和 [ TryInto] 是用于在类型之间进行转换的通用 trait。与 From/Into 不同的是,TryFrom/TryInto trait 用于可能失败的转换,因此返回 [ Result] 类型。

use std::convert::TryFrom;
use std::convert::TryInto;

#[derive(Debug, PartialEq)]
struct EvenNumber(i32);

impl TryFrom<i32> for EvenNumber {
    type Error = ();

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value % 2 == 0 {
            Ok(EvenNumber(value))
        } else {
            Err(())
        }
    }
}

fn main() {
    // TryFrom

    assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
    assert_eq!(EvenNumber::try_from(5), Err(()));

    // TryInto

    let result: Result<EvenNumber, ()> = 8i32.try_into();
    assert_eq!(result, Ok(EvenNumber(8)));
    let result: Result<EvenNumber, ()> = 5i32.try_into();
    assert_eq!(result, Err(()));
}

总结

恭喜你!你已经完成了 TryFromTryInto 实验。你可以在 LabEx 中练习更多实验来提升你的技能。