skip to content

In a Rust order book held as BTreeMap<u64, u32>, how do you remove empty or out-of-band price levels without hitting E0502?

level: middleimportance: should knowfreq 35%

answer

  1. no removing while you borrow
  2. a predicate over every entry
  3. cut the map at one key
  4. a predicate limited to a range
  5. the release that added it

basics

~20 s

Removing inside a for loop over &map fails with E0502. Use retain for a predicate over every entry, split_off to cut the map at a key, or extract_if, stable since Rust 1.91, to remove and collect matches inside one key range.

solid answer

~40 s

A `for (k, v) in &bids` loop holds a shared borrow of the whole map, so calling `bids.remove(k)` inside it is E0502. `BTreeMap` offers three in-place tools instead. `retain(|k, v| ...)` keeps the entries whose predicate returns true and visits keys in ascending order, which suits "drop every level with zero quantity". `split_off(&key)` cuts the map in two: everything at or above the key moves to the returned map and the rest stays, so `bids = bids.split_off(&9_900)` discards every level below 9 900 without running a predicate. `extract_if(range, pred)`, stable since Rust 1.91, visits only that key range and removes and yields the entries the predicate accepts. It is lazy, though: entries it never reaches stay in the map, so an unused `ExtractIf` removes nothing.

code

rust · 10 lines
rust
use std::collections::BTreeMap;

fn main() {
    let mut bids: BTreeMap<u64, u32> = BTreeMap::from([(9_900, 4), (9_950, 0), (10_000, 2)]);
    for (price, qty) in &bids {
        if *qty == 0 {
            bids.remove(price);
        }
    }
}

go deeper

for a junior

Recall that you cannot remove from a map while a for loop borrows it, and that retain removes entries in place.

for a middle

Explain retain's ascending visit, split_off keeping keys below the split key, and extract_if as a lazy, range-limited, must_use iterator from Rust 1.91.

for a senior

Pick the right tool for a hot path: split_off re-links nodes instead of moving entries one by one, and extract_if avoids scanning keys outside the band.

for a principal

Weigh raising a crate's minimum supported Rust version to 1.91 for extract_if against keeping the collect-then-remove workaround for downstream users.

## Why the obvious loop does not compile The first attempt to clean a book usually looks like this: ```rust for (price, qty) in &bids { if *qty == 0 { bids.remove(price); } } ``` The `for` loop holds a **shared borrow** of `bids` for its whole body, and `remove` needs `&mut self`, so rustc rejects it with **E0502** ("cannot borrow `bids` as mutable because it is also borrowed as immutable"). The borrow checker is right: removing nodes under a live iterator would leave it pointing into freed or rebalanced nodes. The general E0502 rules are covered with borrow checker errors. What matters here is that `BTreeMap` ships three tools that remove entries **in place, safely**. ## `retain`: one predicate over every entry `map.retain(|k, v| keep)` removes every entry whose predicate returns `false`. The std docs say elements are **visited in ascending key order**, and the closure gets `&mut V`, so it can also edit the values it keeps. Use it for whole-map rules such as "drop every level whose quantity is zero". In 1.99 `retain` is implemented as `extract_if(.., |k, v| !f(k, v))` drained to the end. ## `split_off`: cut the map at a key `let upper = map.split_off(&key)` splits the collection in two: - the **returned** map holds every key **at or above** `key` (the key itself included); - `map` keeps every key **below** it; - if `key` is absent, the split happens at the next greater key. To discard every level below a cutoff, keep the upper half: `bids = bids.split_off(&cutoff);`. No predicate runs, and entries are not moved one at a time. The implementation cuts the tree along one root-to-leaf path and re-links nodes. It still walks the smaller half's nodes once to count its length. `BTreeSet::split_off` works the same way, and `append` is the inverse that merges another map in. ## `extract_if`: a predicate inside one key range (Rust 1.91) `map.extract_if(range, pred)` became **stable in Rust 1.91**. It takes a key range and a predicate `FnMut(&K, &mut V) -> bool`, visits only the keys inside the range in ascending order, and **removes and yields** each entry the predicate accepts. Points from its docs that interviewers like: - It is **lazy**. If the iterator is dropped before it is exhausted, the remaining elements are **retained**. The type is `#[must_use]`: a bare `m.extract_if(10.., pred);` triggers an `unused_must_use` warning, and with nothing iterated it removes nothing. - If the predicate **panics** on an element, that element stays in the map. - To remove without collecting, use `extract_if(range, pred).for_each(drop)`, or `retain` with a negated predicate when the range is the whole map. Before 1.91, the usual workaround was to collect keys from `range` into a `Vec` and call `remove` for each one, or to run `retain` over the whole map with a range check inside the closure. ## A cleanup pass for an order book Put together, the end-of-tick maintenance of a bid book takes three steps: 1. `bids.retain(|_, qty| *qty > 0)` drops levels that trading emptied; 2. `bids = bids.split_off(&floor)` discards every level below the price band the venue still accepts; 3. `bids.extract_if(trigger.., |_, qty| *qty >= lot)` pulls out the levels that a matching step should process, and hands them over by value. Each step mutates the map in place under one `&mut` borrow, so no step needs a temporary key list or a clone of the map. ## Choosing among them | Task | Tool | Why | |---|---|---| | Drop entries matching a rule, anywhere | `retain` | one pass, ascending order, `&mut V` access | | Drop everything below or above a key | `split_off` | no predicate, re-links nodes | | Remove matches inside one band and use them | `extract_if` (1.91) | visits only the band and yields the removed entries | | Remove one known key | `remove` | a single lookup | ## Mistakes interviewers listen for - Expecting `split_off(&k)` to return the keys **below** `k`. It returns `k` and everything above. - Calling `extract_if` and never iterating it, then wondering why nothing was removed. - Writing `retain` with the predicate inverted. It keeps the entries for which the closure returns `true`. - Reaching for `unsafe` or index tricks to dodge E0502 when an in-place API already exists.

  • What happens if you call BTreeMap::extract_if and never iterate the result?
    Nothing is removed. `ExtractIf` is a lazy iterator: the std docs say that if it is not exhausted, the remaining elements are retained. The type is `#[must_use]`, so rustc warns with `unused_must_use` and suggests `retain` or `extract_if().for_each(drop)` when you only want the entries gone.
  • How do you keep only the levels at or above a cutoff with BTreeMap::split_off?
    `split_off(&cutoff)` returns the keys at or above the cutoff and leaves the lower keys in the original map. Assign the result back with `bids = bids.split_off(&cutoff);` and the old lower half is dropped. To keep the low side instead, call `split_off` and drop or reuse the returned map.
  • Before Rust 1.91, how did code remove matching entries from only one key range?
    One way was to collect the matching keys from `range(...)` into a `Vec`, which ends the shared borrow, then call `remove` for each key. The other was to run `retain` over the whole map with a range check inside the closure. Both still work. `extract_if` replaces them with a single pass limited to the range.

  • Removing from a BTreeMap inside a for loop over it is fine because the tree rebalances.
  • split_off(&k) returns the entries whose keys are below k.
  • extract_if removes matching entries even when its iterator is dropped unused.
  • retain visits entries in arbitrary order, like a HashMap.
  • retain removes the entries for which the closure returns true.

Assumes Rust 1.99; BTreeMap::extract_if and BTreeSet::extract_if are stable since 1.91, while retain (1.53) and split_off (1.11) are much older.