How to store `std::str::Chars` in a struct field of type `Iterator<Item = char>`?

Hi! As a simplified example, I'm trying to create a struct that iterates over chars of str provided to the constructor, five at a time. Internally it just calls .next() five times on the std::str::Chars received from s.chars() and stored in a field of its type. See the working example.

However, I don't use anything specific to std::str::Chars, only the .next() method of the Iterator trait. So, I thought I could specify T: Iterator<Item = char> as a field type where std::str::Chars will be stored. And I tried, but it gives expected type parameter `T`, found struct `Chars` error. See the not working example.
I feel like I'm doing something stupidly wrong, but I just can't find out what.

So, the question is, can I, and if so, how do I store std::str::Chars in a struct field of type Iterator<Item = char>?

Thanks in advance!

In this part of your code,

impl<T> Smth<T>
where
    T: std::iter::Iterator<Item = char>
{
    pub fn new(s: &str) -> Self {
        Self {
            chars: s.chars()
        }
    }

because the impl block is impl<T> Smth<T>, that means Self = Smth<T>, so the return type of new is Smth<T>, but the value returned by the function's body is Smth<std::str::Chars>, which is a mismatch.

The solution is to define this more-specific new() in a more-specific impl block:

impl<'a> Smth<Chars<'a>> {
    pub fn new(s: &'a str) -> Self {
        Self {
            chars: s.chars()
        }
    }
}

Your other method(s) such as print_up_to_five can stay in the impl<T> block.

2 Likes

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.