gpt4 book ai didi

generics - 如果我已经为 U 实现了 From,Rust 是否为 Vec 实现了 From>?

转载 作者:行者123 更新时间:2023-12-03 11:26:28 24 4
gpt4 key购买 nike

我有一个结构 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com