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

标签 generics vector rust traits parametric-polymorphism

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

相关文章:

delphi - 在 Delphi 2009 中如何按字母顺序按键列出 TDictionary?

java - 抽象类中的 Java 可变参数和泛型问题

rust lalrpop 词法歧义 : non-greedy matching inside of brackets

rust - 为 Rust 中的特征提供类似继承的行为

rust - 卡在编译中(substrate-node-template :make build )

c# - 将 ConvertAll 实现为扩展方法

typescript - Typescript 中返回类型的通用映射

c++ - 涉及STL排序算法的令人困惑的SegFault

c++ - 谁应该清除通过引用检索的 vector ?

c++ - 取消引用不适用于 std::vector<std::vector<double>>