Rust的 From 和 Into
实现From
或 Into
这两个 trait, 可以进行类型的转换
如 impl From<B> for A
或 impl 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();
}
此外,还有 TryFrom
和 TryInto
特性,都是实现类型转换,但是用于转换过程中可能出错的情况,其返回值为 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/TryFrom
和 Into/TryInto
,即可对自身类型的转换 T → T
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?