定义

From

From 特性用于定义类型之间的转换。实现 From<T> 可以让类型从 T 转换而来。

RUST
pub trait From<T> {
    fn from(T) -> Self;
    fn try_from(value: T) -> Result<Self, Self::Error>;
}
点击展开查看更多

Into

Into 是 From 的反向操作。如果实现了 From<T>,Rust 会自动提供 Into 的实现。

RUST
pub trait Into<T> {
    fn into(self) -> T;
    fn try_into(self) -> Result<T, Self::Error>;
}
点击展开查看更多

示例

RUST
use std::convert::From;

struct Number {
    value: i32,
}

// 只需实现 From 就自动获得 Into
impl From<i32> for Number {
    fn from(item: i32) -> Self {
        Number { value: item }
    }
}

fn main() {
    // From 的使用方式(明确调用)
    let num1 = Number::from(30);
    
    // Into 的使用方式(需要类型标注)
    let num2: Number = 30.into();
}
点击展开查看更多

版权声明

作者: Chaim

链接: https://chaim.eu.org/posts/from%E5%92%8Cinto/

许可证: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

开始搜索

输入关键词搜索文章内容

↑↓
ESC
⌘K 快捷键