VacantEntry未在名为set的范围内实现任何方法

时间:2015-01-31 08:41:06

标签: hashmap rust

这段代码:

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),
  |                                ^^^

1 个答案:

答案 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);
}

playground