std-method

BTreeMap::range

Select a key interval without building another map. The iterator borrows entries. A reversed interval or equal excluded endpoints can panic; validate user-entered bounds before querying. Expected stdout (not executed): [10, 15] Common mistake: Including 20 in a half-open range.

Formal Syntax & Structure

rust syntaxrust
fn range<T, R>(&self, range: R) -> Range<'_, K, V> where T: Ord + ?Sized, K: Borrow<T> + Ord, R: RangeBounds<T>

Working Example

Example Snippetrust
fn main() {    use std::collections::BTreeMap;    let readings = BTreeMap::from([(5, 20), (10, 23), (15, 25), (20, 28)]);    let selected: Vec<_> = readings.range(10..20).map(|(&t, _)| t).collect();    println!("{selected:?}");}
Rust Reference