A report needs to read the stock, but it does not need its own copy. Returning a Vec of every matching record would allocate and copy names that already exist inside the map. Returning &BTreeMap<String, u32> would avoid the copy but expose the storage type, so switching to a Vec of pairs or a different map later would break every caller. A return type of impl Iterator<Item = (&str, u32)> avoids both costs. Callers learn only that they get an iterator of name and quantity pairs; the concrete adapter type, a Map around a Filter around a btree_map::Iter, stays private to the implementation.
The pairs borrow the names from Stock and copy the quantities, which are cheap u32 values. The filter closure is a move closure so it owns its copy of threshold; without move it would borrow a local parameter that disappears when above returns. The map itself is still borrowed through the underlying iterator, so the compiler ties the returned iterator to &self: it cannot outlive the stock.
Predict and run
Which records survive, and in what order?
use std::collections::BTreeMap;
struct Stock(BTreeMap<String, u32>);
impl Stock {
fn above(&self, threshold: u32) -> impl Iterator<Item = (&str, u32)> + '_ {
self.0.iter()
.filter(move |(_, quantity)| **quantity > threshold)
.map(|(name, quantity)| (name.as_str(), *quantity))
}
}
fn main() {
let stock = Stock(BTreeMap::from([("bolt".into(), 5), ("nut".into(), 2)]));
for (name, quantity) in stock.above(2) {
println!("{name}={quantity}");
}
}Check your prediction
bolt=5nut has exactly 2, and the filter uses >, so the boundary value is excluded. Change the call to stock.above(1) and both lines appear in name order, because the iterator walks the BTreeMap in key order. The double dereference **quantity is there because filter hands its closure a reference to each item, and each item already contains a &u32.
The + '_ at the end of the return type says "this iterator borrows from self". In edition 2024 it is optional: a returned impl Trait automatically captures every lifetime in the signature. Earlier editions captured a lifetime only when it appeared in the bounds, so + '_ was often required, which is why you will still see it in a lot of code.
The borrow lasts as long as the iterator
Because the query borrows the map, the map cannot change while the query is alive. Hold the iterator in a binding and then try to insert:
let big = stock.above(2);
stock.0.insert("washer".into(), 9);
for item in big { println!("{item:?}"); }The compiler rejects it with error[E0502]: cannot borrow stock.0 as mutable because it is also borrowed as immutable. Without that rule, the insert could reorganize the tree while the iterator is walking it. When you genuinely need to read and then modify, copy out exactly what you need first. The copy ends the borrow.
use std::collections::BTreeMap;
struct Stock(BTreeMap<String, u32>);
impl Stock {
fn above(&self, threshold: u32) -> impl Iterator<Item = (&str, u32)> + '_ {
self.0.iter()
.filter(move |(_, quantity)| **quantity > threshold)
.map(|(name, quantity)| (name.as_str(), *quantity))
}
}
fn main() {
let mut stock = Stock(BTreeMap::from([("bolt".into(), 5), ("nut".into(), 2)]));
let restock: Vec<String> = stock.above(0)
.filter(|(_, quantity)| *quantity < 3)
.map(|(name, _)| name.to_owned())
.collect();
for name in &restock {
*stock.0.get_mut(name).unwrap() += 10;
}
println!("{:?}", stock.0);
}{"bolt": 5, "nut": 12}restock owns its Strings, so the query's borrow ended at collect, and the loop is free to mutate. The trade-off is visible: the iterator version costs nothing until it is used, the owned version allocates but is independent of the stock.
Nothing runs until you ask
Iterator adapters are lazy. Building the query does no work at all; each call to next pulls one item through the filter and the map.
use std::collections::BTreeMap;
struct Stock(BTreeMap<String, u32>);
impl Stock {
fn above(&self, threshold: u32) -> impl Iterator<Item = (&str, u32)> + '_ {
self.0.iter()
.filter(move |(_, quantity)| **quantity > threshold)
.map(|(name, quantity)| (name.as_str(), *quantity))
}
}
fn main() {
let stock = Stock(BTreeMap::from([
("bolt".into(), 5), ("nut".into(), 2), ("washer".into(), 8),
]));
let mut query = stock.above(0).inspect(|(name, _)| println!("visited {name}"));
println!("query built");
println!("first: {:?}", query.next());
}query built
visited bolt
first: Some(("bolt", 5))nut and washer were never visited. Laziness is why a borrowed query is cheap to return even for a large map: a caller who wants only the first match, or only a count, pays for exactly that.
Return an iterator, accept a decision later
Returning impl Iterator lets each caller choose: loop over it, collect it into whatever container it needs, or stop early. Returning a Vec makes that choice for everyone, including the allocation.
Practice
Your turn
Add prefix(&self, prefix: &str) that returns a borrowed query of the items whose names start with prefix. The yielded names must borrow from the stock only, so that a caller can collect them and keep the result after the prefix String is gone. With stock bolt=5, bow=1, nut=2, collect stock.prefix(&prefix) inside a block where let prefix = String::from("bo"); lives, and print the result after the block. It should be [("bolt", 5), ("bow", 1)].
use std::collections::BTreeMap;
struct Stock(BTreeMap<String, u32>);
impl Stock {
fn above(&self, threshold: u32) -> impl Iterator<Item = (&str, u32)> + '_ {
self.0.iter()
.filter(move |(_, quantity)| **quantity > threshold)
.map(|(name, quantity)| (name.as_str(), *quantity))
}
}
fn main() {
// Query names starting with a borrowed prefix.
}Hint 1: the idea
The iterator needs both the map and the prefix while it runs, but each yielded name points into the map only. Name the lifetime of &self and use it in Item.
Hint 2: a first step
Start from fn prefix<'s>(&'s self, prefix: &str) -> impl Iterator<Item = (&'s str, u32)>, and use a move closure so the filter owns its copy of the &str.
Worked solution
use std::collections::BTreeMap;
struct Stock(BTreeMap<String, u32>);
impl Stock {
fn prefix<'s>(&'s self, prefix: &str) -> impl Iterator<Item = (&'s str, u32)> {
self.0.iter()
.filter(move |(name, _)| name.starts_with(prefix))
.map(|(name, quantity)| (name.as_str(), *quantity))
}
}
fn main() {
let stock = Stock(BTreeMap::from([("bolt".into(), 5), ("bow".into(), 1), ("nut".into(), 2)]));
let found: Vec<(&str, u32)> = {
let prefix = String::from("bo");
stock.prefix(&prefix).collect()
};
println!("{found:?}");
}[("bolt", 5), ("bow", 1)]The iterator itself captures both lifetimes, so it cannot outlive prefix, but its items carry only 's, so found can. A tempting alternative is a single lifetime for everything, fn prefix<'a>(&'a self, prefix: &'a str) -> impl Iterator<Item = (&'a str, u32)>. It compiles on its own, but the main above then fails with error[E0597]: prefix does not live long enough, because the names now claim to borrow from the prefix too. A signature describes what borrows from what; making it more precise gives callers more freedom.
Completion is saved in this browser only. It does not measure mastery.