TL;DR:更喜欢实现From。
有趣的是,the original RFC 关于 std::convert 特征提出了相反的一揽子实现:
impl<T, U> From<T> for U
where
T: Into<U>
但是在 PR 实施它时,it was changed to the opposite:
添加了From => Into 实现,这使得可以在不违反连贯性的情况下添加双向转换。例如,我们现在有From<[T]> for Vec<T>,其中T: 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。