Learn Rust ยท 6/14

Common Collections: Storing Multiple Values

7 min read

Common Collections: Storing Multiple Values

Welcome back! So far, we've been working with single pieces of data. But in the real world, you often need to handle lists of items, like a user's shopping cart, the players in a game, or the lines in a file. This is where collections come in. They are data structures that can contain multiple values.

Think of it like this: you're not just managing a single student in a school; you're managing all the students. A collection lets you group all those students together and work with them as a single unit.

In this guide, we'll explore three of Rust's most common and powerful collection types:

  • Vectors: For storing a list of values that can grow or shrink.
  • Strings: For working with text.
  • Hash Maps: For storing key-value pairs.

Let's dive in and see how these can make your code more organized and powerful.


Vectors: Storing Lists of Values Dynamically

The Problem: Imagine you're building a music playlist application. Users need to be able to add new songs, remove songs, and reorder their playlist. An array, with its fixed size, just won't cut it here. You need something more flexible.

The Solution: Enter Vec<T>, Rust's vector type. A vector, also known as a dynamic or growable array, allows you to store a variable number of values of the same type next to each other in memory.

Creating a New Vector ๐Ÿ†•

There are a couple of common ways to create a vector.

  1. Vec::new(): This creates a new, empty vector. You'll need to tell Rust the type of data the vector will hold.

    rust
    let mut numbers: Vec<i32> = Vec::new();

    Interesting Fact: When you create an empty vector, Rust needs you to specify the type because it can't guess what you're going to put in it later. It's like telling a librarian you want to start a new collection but not what kind of books it will hold!

  2. The vec! macro: This is the more common and convenient way to create a vector, especially if you have some initial values.

    rust
    let numbers = vec![1, 2, 3, 4, 5];

    Rust is smart enough to infer the type of the vector from the values you provide (i32 in this case).

Updating a Vector โœ๏ธ

To add elements to a vector, you first need to make it mutable using the mut keyword. Then, you can use the push method to add a new element to the end.

rust
let mut numbers = vec![1, 2, 3];
numbers.push(4);
numbers.push(5);
println!("{:?}", numbers); // Output: [1, 2, 3, 4, 5]

Under the Hood: Vectors are stored on the heap, which allows them to resize. When a vector's capacity is exceeded, it will allocate new, larger memory space and copy the existing elements over. It's like moving to a bigger house when your family grows!

Accessing Elements in a Vector ๐Ÿง

You can access vector elements in two ways:

  1. Indexing ([]): This is the most straightforward way. Just remember that indexing starts at 0.

    rust
    let numbers = vec![10, 20, 30, 40, 50];
    let third = &numbers[2];
    println!("The third element is {}", third); // Output: The third element is 30

    Heads up! If you try to access an index that's out of bounds, your program will panic and crash. It's like trying to find a book on a shelf that doesn't exist.

  2. The get method: This method is a safer alternative. It returns an Option<&T>, which will be Some(&value) if the element exists at that index, and None if it doesn't.

    rust
    let numbers = vec![10, 20, 30, 40, 50];
    match numbers.get(2) {
        Some(third) => println!("The third element is {}", third),
        None => println!("There is no third element."),
    }
    
    match numbers.get(100) {
        Some(hundredth) => println!("The hundredth element is {}", hundredth),
        None => println!("There is no hundredth element."), // This will be printed
    }

This approach forces you to handle the possibility of a non-existent element, making your code more robust.


Strings: UTF-8 Text Manipulation ๐Ÿ“

<br> **The Problem:** Your application needs to handle user input, display messages, and work with text in various languages. How do you store and manage this text data efficiently and correctly, especially with the complexities of different languages and characters?

The Solution: Rust provides the String type, a growable, mutable, owned, UTF-8 encoded string. It's the go-to for when you need to modify or own string data.

Creating a New String ๐Ÿ†•

There are a few ways to create a String:

  1. String::new(): To create a new, empty string.

    rust
    let mut s = String::new();
  2. From a string literal (&str): You can use the to_string() method or String::from().

    rust
    let data = "initial contents";
    let s = data.to_string();
    
    // or
    let s = String::from("initial contents");

Fun Fact: Rust's strings are UTF-8 encoded, which means they can handle a vast range of characters from different languages, including emojis! ๐Ÿฆ€๐ŸŽ‰

Updating a String โœ๏ธ

You can grow a String by appending to it.

  1. push_str: Appends a string slice (&str).

    rust
    let mut s = String::from("foo");
    s.push_str("bar");
    println!("{}", s); // Output: foobar
  2. push: Appends a single character.

    rust
    let mut s = String::from("lo");
    s.push('l');
    println!("{}", s); // Output: lol
  3. Concatenation with the + operator: This combines two strings, but it takes ownership of the first string.

    rust
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2; // s1 is moved here and can no longer be used
    println!("{}", s3); // Output: Hello, world!

Accessing Parts of a String (Slicing) ๐Ÿง

Accessing individual characters in a UTF-8 string by index is not straightforward because characters can have different byte sizes. Instead, it's more common to create string slices.

rust
let hello = "ะ—ะดั€ะฐะฒัั‚ะฒัƒะนั‚ะต";
let s = &hello[0..4]; // This will be "ะ—ะด"
println!("{}", s);

Heads up! If you try to slice a String in the middle of a multi-byte character, your program will panic. It's crucial to be careful when slicing strings.


Hash Maps: Storing Keys and Values

The Problem: You're building a system to track the scores of players in a game. You need a way to associate each player's name (a key) with their score (a value) for quick lookups and updates.

The Solution: A hash map, HashMap<K, V>, stores a mapping of keys of type K to values of type V. It's incredibly fast for looking up data.

Creating a New Hash Map ๐Ÿ†•

You can create a new hash map and insert key-value pairs.

rust
use std::collections::HashMap;

let mut scores = HashMap::new();

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

Accessing Values in a Hash Map ๐Ÿง

You can get a value out of a hash map by providing its key to the get method.

rust
use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);

let team_name = String::from("Blue");
let score = scores.get(&team_name);

match score {
    Some(s) => println!("The score is {}", s),
    None => println!("Team not found"),
}

Updating a Hash Map โœ๏ธ

  1. Overwriting a value: If you insert a key that already exists, the old value will be overwritten.

    rust
    use std::collections::HashMap;
    
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Blue"), 25);
    println!("{:?}", scores); // Output: {"Blue": 25}
  2. Only inserting if the key has no value: The entry method is perfect for this.

    rust
    use std::collections::HashMap;
    
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    
    scores.entry(String::from("Yellow")).or_insert(50);
    scores.entry(String::from("Blue")).or_insert(50);
    
    println!("{:?}", scores); // Output: {"Blue": 10, "Yellow": 50}

Real-world scenario: Hash maps are used everywhere, from databases indexing records to compilers keeping track of variable names.


Iterating Over Collections Safely

Iterating is a fundamental operation for collections. Rust's for loop provides a safe and concise way to do this.

Iterating Over a Vector

You can iterate over immutable or mutable references to the elements.

rust
let v = vec![100, 32, 57];
for i in &v {
    println!("{}", i);
}

let mut v = vec![100, 32, 57];
for i in &mut v {
    *i += 50; // Use the dereference operator (*) to modify the value
}
println!("{:?}", v); // Output: [150, 82, 107]

Iterating Over a Hash Map

You can iterate over the key-value pairs in a hash map.

rust
use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

for (key, value) in &scores {
    println!("{}: {}", key, value);
}

A funny exaggeration: Iterating without Rust's safety checks is like juggling chainsaws with your eyes closed. Rust's for loop is your safety goggles and protective gear, ensuring you don't lose a limb (or in this case, cause a data race).


Further Reading ๐Ÿ“š

Challenge

Challenge: Rust Text Analyzer

Your task is to implement the analyze_text function in Rust.

This function will perform a frequency analysis on a given text. It should accept two arguments:

  1. text: A string slice (&str) containing the text to be analyzed.
  2. threshold: A usize value representing the minimum frequency threshold.

The function must perform the following steps:

  • Count the occurrences of each word in the text. Words are defined as sequences of non-whitespace characters.
  • Identify all words that appear strictly more than threshold times.
  • Return a Vec containing tuples of (String, usize), where the first element is the word and the second is its count.
  • This final vector must be sorted by the count in descending order. The relative order of words with the same count is not important.

Expected result

A correct implementation of analyze_text will:

  • Utilize a HashMap to efficiently store and update the frequency of each word. The keys should be of type String and values of type usize.
  • Process the input text by splitting it into words. The split_whitespace() iterator is a standard way to achieve this.
  • Populate the HashMap by iterating over the words. The entry API, specifically or_insert, is the idiomatic approach for incrementing counts.
  • Convert the HashMap into a Vec<(String, usize)> for filtering and sorting.
  • Filter the vector to include only the elements whose count (the second item in the tuple) is strictly greater than the provided threshold.
  • Sort the filtered vector. The sort order must be descending based on the count.
  • Return the final, sorted vector.
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.