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.
答案 0 :(得分:3)
没有必要猜测From
存在Vec
的哪些实现;他们是all listed in the docs。 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> { /**/ }
相反,您需要执行以下操作:
let b: Vec<Wrapper> = a.into_iter().map(Into::into).collect();
如果您尝试实施此操作,则会出现故障:
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`
无法阻止A
和B
相同类型。在这种情况下,您将与From
:impl<T> From<T> for T
的反身实施发生冲突。
另见: