Avn*_*arr 7 generics vector traits rust parametric-polymorphism
我有一个结构NotificationOption
和另一个结构NotificationOption2
以及From<NotificationOption>
for的实现NotificationOption2
。
我想转换Vec<NotificationOption>
为Vec<NotificationOption2>
:
struct NotificationOption {
key: String,
}
struct NotificationOption2 {
key: String,
}
impl From<NotificationOption> for NotificationOption2 {
fn from(n: NotificationOption) -> Self {
Self {
key: n.key,
}
}
}
let options: Vec<NotificationOption> = ...;
let options2: Vec<NotificationOption2> = options.into();
Run Code Online (Sandbox Code Playgroud)
但我收到编译器错误:
struct NotificationOption {
key: String,
}
struct NotificationOption2 {
key: String,
}
impl From<NotificationOption> for NotificationOption2 {
fn from(n: NotificationOption) -> Self {
Self {
key: n.key,
}
}
}
let options: Vec<NotificationOption> = ...;
let options2: Vec<NotificationOption2> = options.into();
Run Code Online (Sandbox Code Playgroud)
Vec<NotificationOption>
似乎不是,这是有道理的 - 您假设从to 的转换Vec<NotificationOption2>
是创建一个Vec<NotificationOption2>
,将NotificationOption
项目转换为NotificationOption2
using.into()
并将它们添加到向量中。Rust 没有理由假设这是转换而不是其他例程。
您也无法From
通用地实现 Vec 到 Vec 因为您的板条箱没有定义From
. 您也许可以创建自己的转换特征,并在Vec<X: Into<Y>>
和之间一般实现它Vec<Y>
。