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项目转换为NotificationOption2using.into()并将它们添加到向量中。Rust 没有理由假设这是转换而不是其他例程。
您也无法From通用地实现 Vec 到 Vec 因为您的板条箱没有定义From. 您也许可以创建自己的转换特征,并在Vec<X: Into<Y>>和之间一般实现它Vec<Y>。