rust-lang / book

The Rust Programming Language
https://doc.rust-lang.org/book/
Other
14.94k stars 3.38k forks source link

Orphan Rule explanation is incomplete #1805

Open CornedBee opened 5 years ago

CornedBee commented 5 years ago

This came up on Reddit: https://www.reddit.com/r/rust/comments/anezli/when_to_use_from_vs_into/efviq8u/?context=3

The book's explanation for the Orphan Rule says that either the trait or the implementing type must be from the current crate. This isn't quite correct, though: if the trait is parametrized, it is also sufficient if the parameter comes from the current crate.

The most likely use case for this is implementing From and Into. The documentation for Into states that I should implement From instead, but the Book would have me believe that this code is not valid:

impl From<MyType> for i32 { ... }

But this code is valid and is the idiomatic way of doing this.

Yet of course the orphan rule is not that simple. In fact, it seems to be quite complicated, and I couldn't find any clear explanation anywhere! There's some design discussion on possible ways in a 2015 blog post here: http://smallcultfollowing.com/babysteps/blog/2015/01/14/little-orphan-impls/

But what I can't find is any definitive documentation on what was actually chosen. The Into documentation shows an example of where things aren't that easy, but I don't actually know why this is so.

So I think that 10.2 (Traits) should have a note indicating that the rule is a bit more nuanced than the simple explanation there, and 19.3 (Advanced Traits) should document the rule more extensively, explaining at least why the above impl works but the example in Into's documentation is necessary.

L0uisc commented 5 years ago

So at least one of the things on the impl line must be local? Either the trait, one of its parameters, or the type for which the trait is implemented?

JakkuSakura commented 7 months ago

Yes, this is very misleading. I've been doing wrong with From and Into for years, under the influence of the book.