rust From 与 Into 特性解析

std::convert::From 与 std::convert::Into

std::convert::From

pub trait From<T>: Sized {
    // Required method
    fn from(value: T) -> Self;
}

#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
impl From<&str> for String {
    /// Converts a `&str` into a [`String`].
    ///
    /// The result is allocated on the heap.
    #[inline]
    fn from(s: &str) -> String {
        s.to_owned()
    }
}
// ...

std::convert::Into

pub trait Into<T>: Sized {
    // Required method
    fn into(self) -> T;
}
// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T
where
    U: From<T>,
{
    /// Calls `U::from(self)`.
    ///
    /// That is, this conversion is whatever the implementation of
    /// <code>[From]&lt;T&gt; for U</code> chooses to do.
    #[inline]
    #[track_caller]
    fn into(self) -> U {
        U::from(self)
    }
}
// ...

实现 From 类型也可自动实现了 Into, 如 String, From 为其实现了 impl From<&str> for String,
所以以下调用是正确的:

let string = String::from("hello");

Into 特性又为 From<T>T 类型提供了实现,以 &str 为例,T&str, UFrom<T>String, 因此这两种类型可相互转换。所以上面的也可以写成:

let string: String = "hello".into();

重要的一点要记住,示例中的 From<T> 类型就是 String!.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值