我有一个结构 NotificationOption
和另一个结构 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>`
Playground link
最佳答案
似乎不是,这是有道理的 - 您假设来自 Vec<NotificationOption>
的转换至 Vec<NotificationOption2>
是创建一个Vec<NotificationOption2>
,转换 NotificationOption
项目成NotificationOption2
使用 .into()
并将它们添加到向量中。 Rust 没有理由假设这是转换而不是其他一些例程。
您也无法实现 From
通常用于 Vec 到 Vec,因为您的箱子没有定义 From
.您或许可以创建自己的转换特征,并在 Vec<X: Into<Y>>
之间一般实现它。和 Vec<Y>
.
关于generics - 如果我已经为 U 实现了 From<T>,Rust 是否为 Vec<U> 实现了 From<Vec<T>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65328977/