我使用HashMap
来存储一些重要数据,我希望能够找到某个键,如果它不存在则为其插入一个值,并且如果找到密钥,则填充到该值。
我将代码简化为错误的最小再现,我并没有真正尝试增加数字。我确实想使用HashMap::Entry
功能,迭代所有键/值都不是替代。
use std::collections::HashMap;
pub fn stack_overflow_example() -> bool {
let hash_map: HashMap<i32, i32> = HashMap::new();
let key = 1;
match hash_map.entry(key) {
HashMap::Entry::Vacant(entry) => entry.insert(vec![1]),
HashMap::Entry::Occupied(entry) => {
let mut numbers = entry.into_mut().iter_mut();
let mut numbers_affected = 0;
for number in numbers {
if number < 10 {
number = number + 1;
numbers_affected += 1;
}
}
if numbers_affected == 0 {
numbers.push(1)
}
}
}
true
}
我收到此错误消息:
error[E0223]: ambiguous associated type
--> src/main.rs:8:9
|
8 | HashMap::Entry::Vacant(entry) => entry.insert(vec![1]),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ambiguous associated type
|
= note: specify the type using the syntax `<std::collections::HashMap<_, _, _> as Trait>::Entry`
error[E0223]: ambiguous associated type
--> src/main.rs:9:9
|
9 | HashMap::Entry::Occupied(entry) => {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ambiguous associated type
|
= note: specify the type using the syntax `<std::collections::HashMap<_, _, _> as Trait>::Entry`
我尝试过它所说的内容,但是当我将这些更改放入时,我无法在(entry)
和Vacant
之后放置Occupied
。以下是错误消息:
error: unexpected `(` after qualified path
--> src/main.rs:8:69
|
8 | <std::collections::HashMap<_, _, _> as Trait>::Entry::Vacant(entry) => entry.insert(vec![1]),
| ^
我应该真的使用&#39; Trait&#39;从字面上?我不知道。我应该用相关类型替换下划线吗?可能,是的,但我仍然得到同样的错误。
答案 0 :(得分:3)
有一个简单的拼写错误。请参阅the documentation for Entry
:
std::collections::hash_map::Entry
您想使用类似
的内容match hash_map.entry(key) {
std::collections::hash_map::Entry::Vacant(entry) => (),
std::collections::hash_map::Entry::Occupied(entry) => (),
}
虽然通常是
use std::collections::hash_map::Entry;
match hash_map.entry(key) {
Entry::Vacant(entry) => (),
Entry::Occupied(entry) => (),
}
这解锁了代码中的许多其他错误:
i32
作为值。请注意,您甚至不需要明确地匹配Entry
。好像代码应该是
pub fn stack_overflow_example(hash_map: &mut HashMap<i32, Vec<i32>>) {
let mut numbers_affected = 0;
let numbers = hash_map.entry(1).or_insert_with(Vec::new);
for number in numbers.iter_mut() {
if *number < 10 {
*number += 1;
numbers_affected += 1;
}
}
if numbers_affected == 0 {
numbers.push(1)
}
}