【问题标题】:Does Rust implement From<Vec<T>> for Vec<U> if I have already implemented From<T> for U?如果我已经为 U 实现了 From<T>,Rust 是否为 Vec<U> 实现 From<Vec<T>>?
【发布时间】:2020-12-16 18:23:09
【问题描述】:

我有一个结构 NotificationOption 和另一个结构 NotificationOption2。我有一个From&lt;NotificationOption&gt; 的实现NotificationOption2

我也在尝试将Vec&lt;NotificationOption&gt; 转换为Vec&lt;NotificationOption2&gt;。我得到一个编译器错误:

#[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

【问题讨论】:

    标签: generics vector rust traits parametric-polymorphism


    【解决方案1】:

    似乎不是,而且它是有道理的 - 您假设从 Vec&lt;NotificationOption&gt;Vec&lt;NotificationOption2&gt; 的转换是创建一个 Vec&lt;NotificationOption2&gt;,使用 .into()NotificationOption 项目转换为 NotificationOption2 并将它们添加到向量。 Rust 没有理由假设这是 转换而不是其他例程。

    您也不能为 Vec 到 Vec 通常实现 From,因为您的 crate 没有定义 From。您也许可以创建自己的转换特征,并在Vec&lt;X: Into&lt;Y&gt;&gt;Vec&lt;Y&gt; 之间通用实现它。

    【讨论】:

    • 但是OP描述的转换是最简单的不丢弃元素的转换。我认为这足以称其为规范的。
    • 如果 Rust 自动提供这种转换,它不允许开发人员编写他们的自定义转换。
    • 你可以在 RFC 中提出建议,但我怀疑它会获得支持
    • @MAHanin - 因为orphan rule,你不能自己写。 Playground
    • 对于 Option 的 From
    【解决方案2】:

    没有,但自己实现很简单:

    let options2: Vec<NotificationOption2> = options.into_iter().map(|x| x.into()).collect();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多