我看到std::convert::Into
对于任何实现的东西都有一个实现std::convert::From
:
impl<T, U> Into<U> for T
where
U: From<T>,
在Rust 1.0标准库中,From
while的许多实现Into
仅在3个地方实现。这使得实现似乎From
是默认设置。我确定有些时候我想实现Into
而不是From
,但是我没有看到它们。
TL; DR:更喜欢实施From
。
有趣的是,有关特征的原始RFCstd::convert
提出了完全相反的实现:
impl<T, U> From<T> for U
where
T: Into<U>
但是在PR实施时,它变成了相反的样子:
添加了
From
=>Into
实现,这使得可以在两个方向上添加转换而不会产生一致性。例如,我们现在有了From<[T]> for Vec<T>
whereT: Clone
,它会产生Into
另一个方向的对应变化-尽管这两种类型生活在不同的板条箱中。我还认为,这解决了一些有关实施的担忧,
From
而不是Into
最后时刻的变化反映了这一点From
,Into
并且基本上是等效的。From
之所以选择它作为首选,是因为从“类型参数与本地类型”的角度来看,限制较少。
在Rust 1.41.0之前,不可能创建impl<'a, T> Into<Foo> for &'a [T]
,而impl<'a, T> From<&'a [T]> for Foo
可能。
第一次尝试提出了E0210
:
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> x.rs:3:10
|
3 | impl<'a, T> Into<Foo> for &'a [T] {
| ^ type parameter `T` must be used as the type parameter for some local type
|
= note: only traits defined in the current crate can be implemented for a type parameter
在Rust 1.14之前的标准库中,只有两个实现示例,Into
而没有From
:
impl Into<Vec<u8>> for String
impl Into<OsString> for PathBuf
我认为这是对接口逻辑的反思。OsString
实现From<String>
和From<T> where T: AsRef<OsStr>
,因为它们是您想要构建的自然对象OsString
。
但是,PathBuf
仍Into<OsString>
作为其From<OsString>
实现的反向操作实现,但是此逻辑属于PathBuf
,而不是OsString
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句