VacantEntry does not implement any method in scope

2019-05-10 06:14发布

问题:

This snippet of code:

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

Gives this error:

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:

VacantEntry doesn't implement any method named set, but there is a method named 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)



标签: hashmap rust