Rust Programming: Create a New Hash Map

0

To create a new hash map in Rust, you can use the new() method on the HashMap struct. This will create an empty hash map with the default capacity. You can also specify a capacity when creating a new hash map, which will preallocate enough space to store that many elements without having to reallocate.

To add elements to a hash map, you can use the insert() method. This method takes two arguments: the key and the value. The key is used to identify the element in the hash map, and the value is the element itself.

Here is an example of how to create a new hash map and add elements to it:

Rust
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    // Get the value for a given key.
    let blue_score = scores.get(&String::from("Blue")).unwrap();

    // Print the value for the "Blue" key.
    println!("The Blue team has {} points.", blue_score);
}

Output:

The Blue team has 10 points.

Hash maps are a very efficient way to store and retrieve data, and they are commonly used in Rust programs. They are particularly well-suited for storing data that needs to be accessed quickly and efficiently, such as caches or lookup tables.

Post a Comment

0Comments
Post a Comment (0)