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.
Vec::new(): This creates a new, empty vector. You'll need to tell Rust the type of data the vector will hold.rustlet 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!
The
vec!macro: This is the more common and convenient way to create a vector, especially if you have some initial values.rustlet numbers = vec![1, 2, 3, 4, 5];Rust is smart enough to infer the type of the vector from the values you provide (
i32in 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.
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:
Indexing (
[]): This is the most straightforward way. Just remember that indexing starts at 0.rustlet numbers = vec![10, 20, 30, 40, 50]; let third = &numbers[2]; println!("The third element is {}", third); // Output: The third element is 30Heads 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.
The
getmethod: This method is a safer alternative. It returns anOption<&T>, which will beSome(&value)if the element exists at that index, andNoneif it doesn't.rustlet 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:
String::new(): To create a new, empty string.rustlet mut s = String::new();From a string literal (
&str): You can use theto_string()method orString::from().rustlet 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.
push_str: Appends a string slice (&str).rustlet mut s = String::from("foo"); s.push_str("bar"); println!("{}", s); // Output: foobarpush: Appends a single character.rustlet mut s = String::from("lo"); s.push('l'); println!("{}", s); // Output: lolConcatenation with the
+operator: This combines two strings, but it takes ownership of the first string.rustlet 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.
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.
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.
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 โ๏ธ
Overwriting a value: If you
inserta key that already exists, the old value will be overwritten.rustuse 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}Only inserting if the key has no value: The
entrymethod is perfect for this.rustuse 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.
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.
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:
text: A string slice (&str) containing the text to be analyzed.threshold: Ausizevalue 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
thresholdtimes. - Return a
Veccontaining 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
HashMapto efficiently store and update the frequency of each word. The keys should be of typeStringand values of typeusize. - Process the input
textby splitting it into words. Thesplit_whitespace()iterator is a standard way to achieve this. - Populate the
HashMapby iterating over the words. TheentryAPI, specificallyor_insert, is the idiomatic approach for incrementing counts. - Convert the
HashMapinto aVec<(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.