[英]If I implement From<A> for B, will From<Vec<A>> for Vec<B> also be implemented?
[英]Does Rust implement From<Vec<T>> for Vec<U> if I have already implemented From<T> for U?
我有一个 struct NotificationOption
和另一个 struct NotificationOption2
。 我有一个From<NotificationOption>
的NotificationOption2
实现。
我也在尝试将Vec<NotificationOption>
转换为Vec<NotificationOption2>
。 我得到一个编译器错误:
#[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>`
似乎没有,这很有意义 - 您假设从Vec<NotificationOption>
到Vec<NotificationOption2>
的转换是创建一个Vec<NotificationOption2>
,使用.into()
将NotificationOption
项转换为NotificationOption2
并将它们添加到向量中。 Rust 没有理由假设这是转换而不是其他例程。
由于您的箱子没有定义From
From
您也许可以创建自己的转换特征,并在Vec<X: Into<Y>>
和Vec<Y>
之间通用地实现它。
它没有,但实现自己很简单:
let options2: Vec<NotificationOption2> = options.into_iter().map(|x| x.into()).collect();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.