我正在尝试从BTreeMap
检索密钥并在后续代码中对其进行操作。
use std::collections::BTreeMap;
fn main() {
let mut map: BTreeMap<u64, u64> = BTreeMap::new();
map.entry(0).or_insert(0);
// It seems like this should work:
let y = map[0] + 1; // expected reference, found integral variable
// Other things I've tried:
let value_at_0 = map[0]; // expected reference, found integral variable
let ref value_at_0 = map[0]; // expected reference, found integral variable
let y = value_at_0 + 1;
let y = (&map[0]) + 1; // expected reference, found integral variable
let y = (&mut map[0]) + 1; // binary operation `+` cannot be applied to type `&mut u64`
let y = (*map[0]) + 1; // type `u64` cannot be dereferenced
println!("{}", y);
}
错误特别令人困惑,因为我认为一个完整的变量正好你可以添加1
的东西。
为了展示我希望这段代码做什么,下面是如何在Python中实现它:
>>> map = {}
>>> map.setdefault(0, 0)
0
>>> y = map[0] + 1
>>> print(y)
1
出于搜索引擎优化的目的,由于我的谷歌搜索失败,更复杂的代码中的原始错误是expected reference, found u64
作为参考,完整的编译错误是:
error[E0308]: mismatched types
--> ./map_weirdness.rs:8:15
|
8 | let y = map[0] + 1; // expected reference, found integral variable
| ^^^^^^ expected reference, found integral variable
|
= note: expected type `&u64`
= note: found type `{integer}`
答案 0 :(得分:0)
该错误发生在传递到[]
的内容中,但错误突出显示整个map[0]
,表明该错误属于的类型map[0]
实际计算值时的值。正确的实现需要传递对[]
的引用,如下所示:
use std::collections::BTreeMap;
fn main() {
let mut map: BTreeMap<u64, u64> = BTreeMap::new();
map.entry(0).or_insert(0);
let y = map[&0] + 1;
println!("{}", y);
}