-
Notifications
You must be signed in to change notification settings - Fork 13.9k
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
Fromshould only be used for inexpensive conversions? (If not, we should probably change the documentation of bothFromandIntoto refrain from saying things about expensiveness). -
The documentation of
Intostates that one should only implementIntoif you want to convert into a type outside your crate.Fromcannot do this as the example shows. However the significant limitation is that you do not get theFromtrait for free, meaning that library authors usingFromas trait bounds cannot automatically use theIntoimplementation. Is there a reason why implementingIntodoes not automatically implementFromas well? -
Intonicely states that it should only be used when implementing traits for types in external crates. Maybe the documentation ofFromshould 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!