How to create a HashMap literal in Rust: macros and manual creation
Hello everyone! I just started learning Rust and I'm having trouble creating a HashMap. In other languages, like Python or JavaScript, you can simply write `{"key": "value"}` and get a dictionary. But in Rust, I can't find a simple way to create a HashMap with initial values.
Here's what I tried:
```rust
use std::collections::HashMap;
fn main() {
// Trying to create a HashMap with a key-value pair
let map = HashMap::new();
map.insert("name", "Alice");
map.insert("age", "30");
println!("{:?}", map);
}
```
But the compiler complains that I'm using `insert` with an immutable variable. I understand that I need to add `mut`, but it's kind of inconvenient. Maybe there's a way to create a HashMap in one line, like in other languages? I've heard about the `vec!` macro.
No answers yet.
Log in to leave an answer