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

Create immutable hash with data

  • HashMap

  • from

  • keys

  • We can also create a HashMap from existing data. In this case the hash does not have to be mutable.

use std::collections::HashMap;

fn main() {
    let counter = HashMap::from([("foo", 1), ("bar", 2)]);
    println!("{:?}", counter);
    println!("{:?}", counter.keys());

    // counter.insert("other", 3); // cannot borrow `counter` as mutable, as it is not declared as mutable
}
{"foo": 1, "bar": 2}
["foo", "bar"]