Rust笔记 - From and Into trait

1,362 阅读1分钟

在Rust中,可以通过FromInto trait,将一个类型转换为另一个类型,并转移所有权。下面看一下定义:

trait Into<T>: Sized {
    fn into(self) -> T;
}

trait From<T>: Sized {
    fn from(T) -> Self;
}

下面看一个实现的例子:

use std::convert::From;
use std::convert::Into;

#[derive(Debug)]
struct Any {
    content: String,
}

impl From<i32> for Any {
    fn from(u: i32) -> Self {
        Any {
            content: format!("{}", u),
        }
    }
}

fn main() {
    let a = Any::from(1) ;
    println!("{:?}", a); // Any { content: "1" }

    let a: Any = 2.into();
    println!("{:?}", a); // Any { content: "2" }
}