Implementing trait with different return type from its methods

Here is pseu-do codes:

struct A { v: Vec<i32> }
struct B { v: Vec<i32> }

trait C {
    fn get(&self) -> &Vec<i32> or Vec<&Vec<i32>>;
}

impl C for A {
    fn get(&self) -> &Vec<i32> {
        &self.v
    }
}
impl C for B {
    fn get(&self) -> Vec<&Vec<i32>> {
        vec![&self.v, &self.v]
    }
}

I tried this, but it does not work:

trait C {
    type Output;
    fn get(&self) -> Self::Output;
}
impl C for A {
    type Output = &Vec<i32>;
    fn get(&self) -> Self::Output {
        &self.v
    }
}
impl C for B {
    type Output = Vec<&Vec<i32>>;
    fn get(&self) -> Self::Output {
        vec![&self.v, &self.v]
    }
}

How can I get to that?

Solution: Output needs a lifetime parameter.

trait C {
    type Output<'a> where Self: 'a;
    fn get<'a>(&'a self) -> Self::Output<'a>;
}

impl C for A {
    type Output<'a> = &'a Vec<i32>;
    fn get<'a>(&'a self) -> Self::Output<'a> {
        &self.v
    }
}
impl C for B {
    type Output<'a> = Vec<&'a Vec<i32>>;
    fn get<'a>(&'a self) -> Self::Output<'a> {
        vec![&self.v, &self.v]
    }
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.