How to elide the lifetime in this trait

struct StringIter<'a> {
    current: Option<&'a String>,
    list: Vec<String>,
    n: usize,
}

trait Iter<'a>{
    fn iter(&'a mut self);
    fn method_a(&'a mut self){self.iter()}
}

impl<'a>Iter<'a> for  StringIter<'a> {
    fn iter(&'a mut self) {
        let mut smallest =None;
        for i in 0..self.n {
            smallest = Some(&self.list[i]);
        }
        self.current = smallest;
    }
}
fn main(){}

The current field need to point to the item in list, so I need to add lifetime to the iter method and the Iter trait to make it compatible with trait.

The code works, but here's my question, there're many structs need to implement the Iter trait, which means they need the lifetime argument too, but the lifetime is only useful for the StringIter. Is there a hack way to elide the lifetime?

This is a self-referential struct and is an antipattern. I'd suggest keeping an Option<usize> as an index rather than a reference to the item.

I'm on mobile, so I can't provide a good explanation as to why they're an antipattern, but it's been explained at length in many posts on this forum and elsewhere. I'd read up on it if I were you.

2 Likes

That's a really really fantastic way to solve my problem! Thank you.

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.