When lazy iterators don't iterate

⚓ Rust    📅 2026-03-08    👤 surdeus    👁️ 1      

surdeus

There were several places in my (small) program where I was using iterators to go through things. However, I found that the iterators were iterating.
In one case, I was using an iterator to search for a name in a vactor, and extract the position and whether I found the name. As a for loop, easy. As an iterator (with the same body, just in a .map(|arg| ...), the iterator never called the map.
In the second case, I was using the iterator to:

    short.iter().map(|ls| {
            if !hm.contains_key(&ls.label) {
                hm.insert(ls.label.clone(), ls.strings.clone());
            } else {
                let mut v1 = hm.get(&ls.label).unwrap().clone();
                v1.extend(ls.strings.clone());
                hm.insert(ls.label.clone(), v1);
            }
    }

Where short is a vector of LabeledStrings (a structure containing a label (string) and a vector of strings). As a for loop, it does exactly what I want. As a .map, it does nothing. Okay. I will use the for loop. But I am clearly misunderstanding something about using iterators. Is the problem that I am copying everything and therefore not consuming the iterator?
Thanks for any explanations,
Joel

5 posts - 2 participants

Read full topic

🏷️ Rust_feed