这段代码:
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;
fn main() {
let mut vars = HashMap::<i32, f64>::new();
let key = 10;
let val = match vars.entry(key) {
Vacant(entry) => entry.set(0.0),
Occupied(entry) => entry.into_mut(),
};
*val += 3.4;
println!("{}", val);
}
给出了这个错误:
error[E0599]: no method named `set` found for type `std::collections::hash_map::VacantEntry<'_, i32, f64>` in the current scope
--> src/main.rs:8:32
|
8 | Vacant(entry) => entry.set(0.0),
| ^^^
答案 0 :(得分:8)
VacantEntry
没有实现名为set
的任何方法,但有一个名为insert
的方法:
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;
fn main() {
let mut vars = HashMap::<i32, f64>::new();
let key = 10;
// vars.insert(key, 25.0);
let val = match vars.entry(key) {
Vacant(entry) => entry.insert(0.0),
Occupied(entry) => entry.into_mut(),
};
*val += 3.4;
println!("{}", val);
}