【问题标题】:Return generic Vec返回通用 Vec
【发布时间】:2020-08-13 11:16:36
【问题描述】:

假设我有一个这样的结构:

struct A {
    field0: u32,
    field1: Vec<B>,
}

struct B {
    field0: f64,
    field1: String,
    field2: Vec<C>,
}

struct C {
    field0: Vec<u8>,
    field1: bool,
}

我想为每个输出带有 Vec 的字段的结构实现一个特征。

// snip
trait MyVec<T> {
    fn myvec(&self) -> Vec<T>;
}

impl MyVec<T> for A {
    fn myvec(&self) -> Vec<T> { // return Vec<B>
        &self.field1
    }
}
impl MyVec<T> for B {
    fn myvec(&self) -> Vec<T> { // return Vec<C>
        &self.field2
    }
}
impl MyVec<T> for C {
    fn myvec(&self) -> Vec<T> { // return Vec<u8>
        &self.field0
    }
}

但是编译器抱怨expected type parameter T but found struct B。我该如何正确地做到这一点?

对不起,如果这是个愚蠢的问题,我对 Rust 很陌生,对泛型或特征一无所知。

【问题讨论】:

    标签: generics struct rust traits


    【解决方案1】:

    您需要指定T。即:

    impl MyVec<B> for A {
        fn myvec(&self) -> Vec<B> {
            &self.field1
        }
    }
    

    也就是说,A 不为任意 T 实现MyVec&lt;T&gt; - 它只为B 实现它。

    您也可以删除类型参数并改用关联类型:

    trait MyVec {
        type Item;
        fn myvec(&self) -> Vec<Self::Item>;
    }
    
    impl MyVec for A {
        type Item = B;
        fn myvec(&self) -> Vec<B> {
            &self.field1
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-28
      • 2015-11-30
      • 1970-01-01
      • 2020-09-11
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      相关资源
      最近更新 更多