I have a struct NotificationOption
and another struct NotificationOption2
. I have an implementation for From<NotificationOption>
for NotificationOption2
.
I'm also trying to convert Vec<NotificationOption>
to a Vec<NotificationOption2>
. I get a compiler error:
#[derive(Clone)]
pub struct NotificationOption {
pub key: String,
}
#[derive(Serialize, Deserialize)]
pub struct NotificationOption2 {
pub key: String,
}
impl From<NotificationOption> for NotificationOption2 {
fn from(n: NotificationOption) -> Self {
Self {
key: n.key,
}
}
}
let options : Vec<NotificationOption> = Vec::new();
/// add some options...
// some other point in code
let options2: Vec<NotificationOption2> = options.into();
| ^^^^ the trait `std::convert::From<std::vec::Vec<NotificationOption>>` is not implemented for `std::vec::Vec<NotificationOption2>`
Seems not, and it makes sense - you assume that the conversion from Vec<NotificationOption>
to Vec<NotificationOption2>
is to create a Vec<NotificationOption2>
, convert the NotificationOption
items into NotificationOption2
using .into()
and add them to the vector. Rust has no reason to assume this is the conversion and not some other routine.
You also can't implement From
generically for a Vec to Vec since your crate didn't define From
. You can perhaps create a conversion trait of your own, and implement it generically between Vec<X: Into<Y>>
and Vec<Y>
.
It doesn't, but it's trivial to implement yourself:
let options2: Vec<NotificationOption2> = options.into_iter().map(|x| x.into()).collect();
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.