我有一个BTreeMap
使用二元组键 存储项目的位置,(String, i32)
因此存储整数的映射类型是BTreeMap<(String, i32), i32>
。
有没有办法使用二元组的第一个元素来查找元素?例如某种形式的自定义范围?我该怎么做呢?
一个简短的例子:
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(), _));
}
您可以使用
BTreeMap::range
以下方法来执行此操作:(游乐场)
请注意,由于该
Borrow
特征的工作方式,不幸的是您必须分配两个字符串,一个用于范围的每一端。