Wrong number of lifetime parameters when using the modified `Chars` iterator

I want to implement a trait IntoIteratorfor a structure containing String. The iterator is based on an iterator chars(), it is supposed to read the characters '1'and copy the result. This is a simplified version of what I have received so far:

use std::iter::Map;
use std::str::Chars;

fn main() {
    let str_struct = StringStruct { system_string: String::from("1101") };
    for a in str_struct {
        println!("{}", a);
    }
}

struct StringStruct {
    system_string: String
}

impl IntoIterator for StringStruct {
    type Item = u32;
    type IntoIter = Map<Chars, Fn(char) -> u32>;

    fn into_iter(self) -> Self::IntoIter {
        let count = 0;
        return self.system_string.chars().map(|c| match c {
            Some('1') => {
                count += 1;
                return Some(count);
            },
            Some(chr) => return Some(count),
            None => return None
        });
    }
}

Expected Result: 1, 2, 2, 3

This fails:

error[E0107]: wrong number of lifetime parameters: expected 1, found 0
  --> src/main.rs:17:25
   |
17 |     type IntoIter = Map<Chars, Fn(char) -> u32>;
   |                         ^^^^^ expected 1 lifetime parameter

The character iterator should have the same lifetime as it is StringStruct::system_string, but I have no idea how to express it or if this approach is viable at all.

+4
source share
1 answer

, impl IntoIterator for &StringStruct (a StringStruct ). :

impl<'a> IntoIterator for &'a StringStruct {
    type Item = u32;
    type IntoIter = Map<Chars<'a>, Fn(char) -> u32>;
    // ...
}

, , . , , , Fn(char) -> u32 .

, , Fn(char) -> u32. , , . ( " " ).

, Map<_, _>. ; impl Trait -RFC . , , .

, ? , Iterator Map<_, _>. , Chars. :

struct StringStructIter<'a> {
    chars: Chars<'a>,
    count: u32,
}

impl<'a> Iterator for StringStructIter<'a> {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
         self.chars.next().map(|c| {
            if c == '1' {
                self.count += 1;
            }
            self.count
        })
    }
}

impl<'a> IntoIterator for &'a StringStruct {
    type Item = u32;
    type IntoIter = StringStructIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
         StringStructIter {
             chars: self.system_string.chars(),
             count: 0,
         }
    }
}

fn main() {
    let str_struct = StringStruct { system_string: String::from("1101") };
    for a in &str_struct {
        println!("{}", a);
    }
}

: return, , Rust. , return, ; -)

+5

Source: https://habr.com/ru/post/1657850/


All Articles