简体   繁体   中英

If I implement From<A> for B, will From<Vec<A>> for Vec<B> also be implemented?

It seems like no, because I have code that implements From<A> for <B> , and I can convert an A to a B with .into() , but the same thing isn't working for a Vec<A> .into() a Vec<B> .

Either I've screwed up something that's preventing the implementation from being derived, or this isn't supposed to happen.

If it's not supposed to work, why not? It seems like code such as this would work:

impl<A: From<B>, B> From<Vec<A>> for Vec<B> {
    // ... map .into onto vec of As to vec of Bs ...
}

I'm guessing there's more complexity to it than that.

There's no need to guess at which implementations of From exist for Vec ; they are all listed in the docs . The list as of Rust 1.21.0:

impl<'a, T> From<&'a mut [T]> for Vec<T> { /**/ }

impl<T> From<BinaryHeap<T>> for Vec<T> { /**/ }

impl<T> From<VecDeque<T>> for Vec<T> { /**/ }

impl<'a, T> From<&'a [T]> for Vec<T>  { /**/ }

impl From<String> for Vec<u8> { /**/ }

impl<'a, T> From<Cow<'a, [T]>> for Vec<T> { /**/ } 

impl<'a> From<&'a str> for Vec<u8> { /**/ }

impl<T> From<Box<[T]>> for Vec<T> { /**/ }

Instead, you will want to do something like:

let b: Vec<Wrapper> = a.into_iter().map(Into::into).collect();

If you tried to implement this, you'd get a failure:

error[E0119]: conflicting implementations of trait `core::convert::From<vec::Vec<_>>` for type `vec::Vec<_>`:
    --> /Users/shep/Projects/rust/src/liballoc/vec.rs:2190:1
     |
2190 | / impl<A, B> From<Vec<A>> for Vec<B>
2191 | |     where A: Into<B>
2192 | | {
2193 | |     fn from(s: Vec<A>) -> Vec<B> {
2194 | |         s.into_iter().map(Into::into).collect()
2195 | |     }
2196 | | }
     | |_^
     |
     = note: conflicting implementation in crate `core`

Nothing prevents A and B from being the same type . In that case, you'd be conflicting with the reflexive implementation of From : impl<T> From<T> for T .

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM