BTreeMap Reverse Iteration Walk

BTreeMap iterates keys in ascending order; iter().rev() walks the same tree from the largest key down without sorting or reversing a Vec.

RustData Integrity

Code

rustsnippet
22 lines
use std::collections::BTreeMap;

fn main() {
    let mut commits = BTreeMap::new();
    commits.insert(101, "init");
    commits.insert(103, "fix parser");
    commits.insert(105, "add tests");

    // BTreeMap already iterates in ascending key order
    for (id, message) in &commits {
        println!("asc {id}: {message}");
    }

    // iter().rev() walks the same tree backward from the largest key
    let mut latest = commits.iter().rev();
    let (id, message) = latest.next().expect("non-empty map");
    println!("newest: {id}: {message}");

    for (id, message) in commits.iter().rev() {
        println!("desc {id}: {message}");
    }
}

How it works

The code’s whole job belongs to the function main.

One loop does the cycling here: for (id, message) in &commits.

Points of care

  • The toolchain already provides everything it needs in order to run.

Using it

Signature: fn main()

Look for the asc, newest:, desc prefixes during the file’s run; they match each line of output to the step that emitted it.

Key statements

for (id, message) in commits.iter().rev() {
    println!("desc {id}: {message}");
}
let mut latest = commits.iter().rev();

Interactive Tools for This Topic

FAQ

What does BTreeMap Reverse Iteration Walk print when run?
Run it as a complete program — the output lines carry labels such as `asc`, `newest:`, `desc`.