Search code examples
rustiteratorcharlifetime

Wrapping Chars into_iter()


I have this simple struct:

struct MyStruct {
    text: String,
}

And want to implement the IntoIterator trait for it. Since Chars already implements it, I just want to wrap it:

impl IntoIterator for MyStruct {
    type Item = char;
    type IntoIter = std::str::Chars;

    fn into_iter(self) -> Self::IntoIter {
        self.text.chars().into_iter()
    }
}

This results in missing lifetime specifier errors since Chars needs a lifetime specifier.

I was able to solve this by implementing my own iterator. But I wonder if it is possible just to wrap the iterator of Chars.


Solution

  • You can implement it for a reference to your type instead:

    impl<'a> IntoIterator for &'a MyStruct {
        type Item = char;
        type IntoIter = std::str::Chars<'a>;
    
        fn into_iter(self) -> Self::IntoIter {
            self.text.chars()
        }
    }
    

    There's no other way to achieve it without a custom OwnedChars, since IntoIter must own the String in your struct, but Chars can only hold an &str.