Description
Description
I was reading on the From and Into traits and I got a little confused:
From
states:
Simple and safe type conversions in to Self.
whereas Into
states:
A conversion that consumes self, which may or may not be expensive.
The Problem
This makes it seem like implementing From
should be used for implementing relatively cheap operations (interpreting the word 'simple' as 'cheap') automatically gaining Into
for free. Whereas implementing Into
(and therefore not getting the From
trait for free) should be used for expensive conversions.
However later in the documentation of Into
states:
Library authors should not directly implement this trait, but should prefer implementing the From trait, which offers greater flexibility and provides an equivalent Into implementation for free, thanks to a blanket implementation in the standard library.
which in turns suggests that one should not implement Into
at all (unless you want to convert into a type outside your crate).
Now I have 3 questions:
-
Is it true, that
From
should only be used for inexpensive conversions? (If not, we should probably change the documentation of bothFrom
andInto
to refrain from saying things about expensiveness). -
The documentation of
Into
states that one should only implementInto
if you want to convert into a type outside your crate.From
cannot do this as the example shows. However the significant limitation is that you do not get theFrom
trait for free, meaning that library authors usingFrom
as trait bounds cannot automatically use theInto
implementation. Is there a reason why implementingInto
does not automatically implementFrom
as well? -
Into
nicely states that it should only be used when implementing traits for types in external crates. Maybe the documentation ofFrom
should also note this?
I am curious on what you all think!
Disclaimer: I have been using Rust for the last 4 months, so I would not consider myself an expert. So if I am wrong on some points or misunderstand anything, please correct me!