Why From trait vs Into trait?

Rust by example and the stdlib entries say to prefer implementing From instead of Into.
Why? I believe From comes with an implementation of Into. Can that only go one way, because of circular references somehow? And so we just had to choose one or the other to be preferred?

Yes, From implies Into, but Into does not imply From. This is because they have different definitions, and you can implement Into on types from other crates, but not From.

The reason for this distinction is that, due to Rust’s coherence rules (also known as orphan rules), some implementations of From are impossible to write

for example, this doesn’t compile

struct Foo<T>(T);

impl<T> From<Foo<T>> for Vec<T> {
    fn from(foo: Foo<T>) -> Self {
        vec![foo.0]
    }
}

So to get around this, you can write an Into impl instead

struct Foo<T>(T);

impl<T> Into<Vec<T>> for Foo<T> {
    fn into(self) -> Vec<T> {
        vec![self.0]
    }
}

But now we have two traits that serve the exact same purpose. So Rust gave an implementation to convert from one trait to the other. It was decided to be an impl of From gives you an impl of Into.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.