Search code examples
rustbtreemap

How to lookup from BTreeMap with a two-tuple as key, using the first element?


I have a BTreeMap where I store items using a two-tuple key, (String, i32), so the type of map that stores integers is BTreeMap<(String, i32), i32>.

Is there a way I can lookup elements by using the first element of the two-tuple? E.g. some form of custom range? How would I do that?

A short example:

use std::collections::BTreeMap;

fn main() {
    let mut m : BTreeMap<(String, i32), i32> = BTreeMap::new();
    m.insert(("hello".to_string(), 12), 34);
    m.insert(("hello".to_string(), 4), 56);
    m.insert(("other".to_string(), 4), 44);

    let one_element = m.get(&("hello".to_string(), 12));
    println!("{:?}", one_element);

    // does not work, perhaps some custom range could be used?
    let all_hello = m.get(&("hello".to_string(), _));
}

Solution

  • You can use BTreeMap::range to do this:

    let range = m.range(("hello".to_string(), i32::MIN)..=("hello".to_string(), i32::MAX));
    
    for item in range {
        println!("{:?}", item);
    }
    

    (Playground)

    Note that because of the way the Borrow trait works, you unfortunately have to allocate two strings, one for each end of the range.