rust - When should I implement std::convert::From vs std::convert::Into? -
i see std::convert::into has implementation implements std::convert::from:
impl<t, u> into<u> t u: from<t> there far more specific implementations of from, while into has 3 specific implementations, makes seem prevailing decision implement from default. i'm there times want implement into , not from, i'm not seeing them.
interestingly, the original rfc std::convert traits suggesting opposite blanket impl:
impl<t, u> from<t> u t: into<u> but on pr implementing it, it changed opposite:
added
from=>intoimplementation, makes possible add conversions in both directions without running afoul of coherence. example, havefrom<[t]> vec<t> t: clone, yields corresponding going in other direction -- despite fact 2 types live in different crates.i believe addresses few concerns things implementing instead of into
it indeed not possible make impl<'a, t> into<foo> &'a [t], while impl<'a, t> from<&'a [t]> foo possible.
the first attempt raises e0210:
error: type parameter
tmust used type parameter local type (e.g.mystruct<t>); traits defined in current crate can implemented type parameter
but change @ last moment reflect from , into equivalent. from chosen preferred 1 less restrictive "type parameter vs. local type" point of view.
there in standard library 2 examples of implementing into , not from:
impl into<vec<u8>> string impl into<osstring> pathbuf but think reflexion of logic of interfaces. osstring implements from<string> , from<t> t: asref<osstr>, because natural things you'll want build osstring from.
however, pathbuf still implement into<osstring> reverse operation of from<osstring> implementation, logic belongs pathbuf, not osstring.