Return generic Vec

Viewed 61

Say I have a struct like this:

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

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

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

I want to implement a trait for each struct which outputs field with a Vec in it.

// 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
    }
}

But compiler complains expected type parameter T but found struct B. How do I do this properly?

Sorry if this is stupid question, I am very new to Rust and don't know first thing about generics or traits.

1 Answers

You need to specify T. i.e.:

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

That is, A doesn't implement MyVec<T> for any arbitrary T - it only implements it for B.

You could also remove the type parameter and use an associated type instead:

trait MyVec {
    type Item;
    fn myvec(&self) -> Vec<Self::Item>;
}

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