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 => into implementation, makes possible add conversions in both directions without running afoul of coherence. example, have from<[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 t must 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.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -