Rust的 From 和 Into

实现FromInto 这两个 trait, 可以进行类型的转换

impl From<B> for Aimpl Into<B> for A,则有 B → A 这种类型转换,一般只需要实现 From,就可以自动实现 Into

struct A;
struct B;

// 实现了 From 会自动实现 Into
impl From<B> for A{
    fn from(value: B) -> Self{
        A
    }  
}

fn main(){
  let b: B = B;
  // From:通过 b 来创建 A
  let a: A = A::from(b);
  // Into:将 b 转变为 A,还需指明类型A
  let a: A = b.into();
}

此外,还有 TryFromTryInto 特性,都是实现类型转换,但是用于转换过程中可能出错的情况,其返回值为 Result

impl TryFrom<B> for A ,则有 B → Result<A,Error>

// 将容易出错的转变
impl TryFrom<B> for A {
    type Error = ();

    fn try_from(value: B) -> Result<Self, Self::Error> {
        let flag = true;
        if flag {
            Ok(A)
        } else {
            Err(())
        }
    }
}

总结,Rust 中,所有的类型 T 都实现了 From/TryFromInto/TryInto,即可对自身类型的转换 T → T

posted @   ~哥斯拉~  阅读(683)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示