我应该什么时候实施 std::convert::From 与 std::convert::Into?

When should I implement std::convert::From vs std::convert::Into?

我看到 std::convert::Into has an implementation for anything that implements std::convert::From:

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

在 Rust 1.0 标准库中,From 有很多实现,而 Into 只在 3 个地方实现。这使得实现 From 似乎应该是默认的。我确定有时我想实现 Into 而不是 From,但我没有看到它们。

TL;DR:更喜欢实施 From.


有趣的是,the original RFC about the std::convert traits 提出了相反的全面实施:

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

这个最后一刻的变化反映了 FromInto 基本上是等价的。 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