Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust update values in a hash - count words

  • entry
  • or_insert}
use std::collections::HashMap;

fn main() {
    let fruits = ["apple", "banana", "peach", "apple"];
    let mut counter = HashMap::new();

    for fruit in fruits {
        println!("{}", fruit);
        *counter.entry(fruit).or_insert(0) += 1;
    }
    println!("{:#?}", counter);
}