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]<T> 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, U 是 From<T> 即 String, 因此这两种类型可相互转换。所以上面的也可以写成:
let string: String = "hello".into();
重要的一点要记住,示例中的 From<T> 类型就是 String!.
894

被折叠的 条评论
为什么被折叠?



