簡體   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