跳转到主要内容
eLearner.app
模块 7 · 第 1 课(共 2)课程中的13/14~12 min
模块课程(1/2)

集合和 HashMap

Collections are data structures capable of holding multiple values. Unlike the primitive array and tuple types, the data these collections reference is stored on the heap, which means the amount of data does not need to be known at compile time and can grow or shrink dynamically during program execution.

The two most commonly used collections in Rust are vectors (Vec<T>) and key-value maps (HashMap<K, V>).


Vectors (Vec<T>)

Vectors allow you to store more than one value of the same type in a single data structure that puts all values next to each other in memory:

Code
fn main() {
    // Creating an empty mutable vector
    let mut v: Vec<i32> = Vec::new();

    // Or using the vec! macro
    let mut v2 = vec![1, 2, 3];

    // Appending elements
    v.push(5);
    v.push(6);

    // Accessing elements by index
    let third = v2[2];
    println!("The third element is: {}", third);
}

HashMap (HashMap<K, V>)

The HashMap<K, V> collection stores a mapping of keys of type K to values of type V. It operates via a hashing function, which determines how these keys and values are placed in memory. It is extremely useful when you want to look up data not by a numeric index, but by a key (such as a name or an ID).

Code
use std::collections::HashMap;

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

    // Inserting key-value pair
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    // Reading a value (returns an Option<&V>)
    let team_name = String::from("Blue");
    let score = scores.get(&team_name);

    match score {
        Some(val) => println!("Score: {}", val),
        None => println!("No score found."),
    }
}

Try it yourself

Exercise 1: Basic Operations on Vec

锻炼#rust.m7.l1.e1
尝试:0加载中...

Declare a mutable integer vector named v using Vec::new(). Add the elements 10, 20, and 30 in sequence using the push method. Finally, print the first element of the vector (index 0) using println!.

正在加载编辑器...
显示提示

Use `let mut v = Vec::new();` to initialize the vector, insert elements with `v.push(value)` and access with `v[0]`.

3 次尝试后可用的解决方案

Exercise 2: User Scores with HashMap

锻炼#rust.m7.l1.e2
尝试:0加载中...

Import std::collections::HashMap. In the main function, declare a mutable HashMap named scores to store String keys and i32 values. Insert a score of 50 for the user 'Alice'. Safely extract the score using the get method and unwrap() to print it.

正在加载编辑器...
显示提示

Do not forget `use std::collections::HashMap;`. Insert with `scores.insert(String::from("Alice"), 50);`and fetch the value with`.get("Alice").unwrap()`.

3 次尝试后可用的解决方案

Exercise 3: Doubling Values in a Vector

锻炼#rust.m7.l1.e3
尝试:0加载中...

Define a function named double_values that accepts a reference to a slice of integers &[i32] and returns a new Vec<i32> containing the same elements multiplied by 2.

正在加载编辑器...
显示提示

The function should iterate over the elements of the slice and insert them multiplied by 2 into the new vector to be returned.

3 次尝试后可用的解决方案