RRust By Example
intermediateCollections

BTreeMap

Sorted key-value map with B-tree implementation.

BTreeMap

Sorted key-value map with B-tree implementation.

Difficulty

Intermediate

Code

rust
use std::collections::BTreeMap;

fn main() {
    let mut map = BTreeMap::new();
    map.insert("three", 3);
    map.insert("one", 1);
    map.insert("two", 2);

    // keys are always sorted
    for (key, value) in &map {
        println!("{}: {}", key, value);
    }
}

Explanation

This example demonstrates how to use btreemap in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples