繁体   English   中英

Rust 是否执行自<vec<t> &gt; 对于 Vec <u>,如果我已经实现 From</u><t> <u>为了你?</u> </t></vec<t>

[英]Does Rust implement From<Vec<T>> for Vec<U> if I have already implemented From<T> for U?

我有一个 struct NotificationOption和另一个 struct 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>`

游乐场链接

似乎没有,这很有意义 - 您假设从Vec<NotificationOption>Vec<NotificationOption2>的转换是创建一个Vec<NotificationOption2> ,使用.into()NotificationOption项转换为NotificationOption2并将它们添加到向量中。 Rust 没有理由假设这转换而不是其他例程。

由于您的箱子没有定义From From 您也许可以创建自己的转换特征,并在Vec<X: Into<Y>>Vec<Y>之间通用地实现它。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM