![](/img/trans.png)
[英]If I implement From<A> for B, will From<Vec<A>> for Vec<B> also be implemented?
[英]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.