مرکزی مواد پر جائیں
eLearner.app
ماڈیول 7 · سبق 1 از 2کورس میں 13/14~12 min
ماڈیول اسباق (1/2)

مجموعے اور ہیش میپ

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 کوششوں کے بعد حل دستیاب ہے۔