3

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),
  |                                ^^^
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Gigih Aji Ibrahim
  • 405
  • 1
  • 3
  • 10

1 Answers1

8

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)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
defyrlt
  • 136
  • 4
  • thanks. https://github.com/eliovir/rust-examples/blob/master/api-collections-hashmap.rs give me wrong example :( – Gigih Aji Ibrahim Jan 31 '15 at 12:06
  • @GigihAjiIbrahim Rust is changing rapidly in the runup to 1.0. Your best bet is to refer to the [official documentation site](http://doc.rust-lang.org/). Most (if not all) of the code examples there are compiled and tested against the current state of the language, so it's a good bet they will be correct. – Shepmaster Jan 31 '15 at 14:42