Trait core::convert::Into 1.0.0[−][src]
Expand description
消耗输入值的值到值转换。与 From 相反。
应该避免实现 Into,而应实现 From。
由于标准库中的全面实现,因此 From 的自动实现为 Into 的实现提供了一个实现。
在泛型函数上指定 trait bounds 时,最好使用 Into 而不是 From,以确保也可以使用仅实现 Into 的类型。
注意:此 trait 一定不能失败。如果转换可能失败,请使用 TryInto。
泛型实现
在旧版本的 Rust 中实现 Into 转换为外部类型
在 Rust 1.41 之前,如果目标类型不是当前 crate 的一部分,那么您将无法直接实现 From。
例如,使用以下代码:
struct Wrapper<T>(Vec<T>);
impl<T> From<Wrapper<T>> for Vec<T> {
fn from(w: Wrapper<T>) -> Vec<T> {
w.0
}
}Run由于 Rust 的孤儿规则过去要严格一些,因此无法在较旧的语言版本中进行编译。
要绕过它,您可以直接实现 Into:
struct Wrapper<T>(Vec<T>);
impl<T> Into<Vec<T>> for Wrapper<T> {
fn into(self) -> Vec<T> {
self.0
}
}Run重要的是要了解 Into 不提供 From 实现 (就像 From 与 Into 一样)。
因此,您应该始终尝试实现 From,如果无法实现 From,则应回退到 Into。
Examples
为了表示我们希望泛型函数采用所有可以转换为指定类型 T 的参数,我们可以使用 Into<T> 的 trait bound。
例如:函数 is_hello 接受所有可以转换为 Vec<u8> 的参数。
fn is_hello<T: Into<Vec<u8>>>(s: T) {
let bytes = b"hello".to_vec();
assert_eq!(bytes, s.into());
}
let s = "hello".to_string();
is_hello(s);Run