2015-04-23 46 views

回答

18

有趣的是,the original RFC有关std::convert特点是暗示相反毯IMPL:

impl<T, U> From<T> for U where T: Into<U> 

但在PR实现它,it was changed to the opposite

Added From =>Into implementation, which makes it possible to add conversions in both directions without running afoul of coherence. For example, we now have From<[T]> for Vec<T> where T: Clone , which yields the corresponding Into going in the other direction -- despite the fact that the two types live in different crates.

I also believe this addresses a few concerns about things implementing From instead of Into

这的确是不可能做出impl<'a, T> Into<Foo> for &'a [T] ,而impl<'a, T> From<&'a [T]> for Foo是可能的。

第一次尝试提出了一个E0210

error: type parameter T must be used as the type parameter for some local type (e.g. MyStruct<T>); only traits defined in the current crate can be implemented for a type parameter

但这种变化在最后时刻反映FromInto基本上是等价的。 From被选为首选,因为从“类型参数与本地类型”的角度来看,它的限制性较小。

有在标准库中仅有的两个实施Into的例子,而不是From

但他们是我认为其接口逻辑的反思。 OsString implements From<String>From<T> where T: AsRef<OsStr>,因为它们是您想要从中构建OsString的自然事物。

然而,PathBuf仍然实现Into<OsString>作为From<OsString>实施的扭转操作,但这种逻辑是属于PathBuf,不OsString

+2

*'PathBuf'仍然执行'Into '*←这已在1.14.0:D中修复。在标准库中没有任何impl'Into <*>'。 – kennytm