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/

相关文章:

python - 如何向量化__call__方法

rust - 从结构方法中创建和分配引用数据

pointers - 对矢量的引用仍打印为矢量?

java - 另一个对泛型感到困惑的可怜人......如何在这段代码中添加静态 .start() 方法?

c++ - 复合数据结构和摆弄指针

java - Void 方法缺少返回值?

c++ - C++ 中是否有标准的 3d vector 类

rust - 如何解析 Rust 宏中的单个标记

java - 返回类型中的推断通配符泛型

c# - 通用列表/子列表处理