Collections: Vectors, Strings, and HashMaps – in Rust
Welcome to this comprehensive, student-friendly guide on collections in Rust! Whether you’re a beginner or have some programming experience, this tutorial will help you understand and master vectors, strings, and hashmaps in Rust. Let’s dive in and make learning fun! 🚀
What You’ll Learn 📚
- Understanding the basics of collections in Rust
- How to use vectors, strings, and hashmaps effectively
- Common pitfalls and how to avoid them
- Practical examples and exercises to solidify your knowledge
Introduction to Collections in Rust
In Rust, collections are data structures that allow you to store and manage multiple values. The most commonly used collections are vectors, strings, and hashmaps. Each of these has its own unique characteristics and use cases.
Key Terminology
- Vector: A resizable array that can store elements of the same type.
- String: A collection of characters, used for storing text.
- HashMap: A collection of key-value pairs, similar to a dictionary in other languages.
Vectors: The Basics
Vectors are like arrays but more flexible. They can grow or shrink in size. Let’s start with the simplest example:
fn main() { let mut numbers = vec![1, 2, 3]; // Create a vector of integers numbers.push(4); // Add an element to the end println!("{:?}", numbers); // Output: [1, 2, 3, 4] }
In this example, we created a vector of integers and added an element using push
. The println!
macro is used to print the vector.
Progressively Complex Examples
Example 1: Iterating Over a Vector
fn main() { let numbers = vec![1, 2, 3, 4, 5]; for number in &numbers { println!("{}", number); } }
Here, we iterate over the vector using a for
loop. The &numbers
gives us a reference to the vector, allowing us to iterate without taking ownership.
Example 2: Modifying a Vector
fn main() { let mut numbers = vec![1, 2, 3]; for number in &mut numbers { *number *= 2; } println!("{:?}", numbers); // Output: [2, 4, 6] }
In this example, we modify each element in the vector by doubling its value. The &mut numbers
allows us to mutate the vector.
Strings: Handling Text
Strings in Rust are UTF-8 encoded, making them suitable for storing text. Here’s a simple example:
fn main() { let mut greeting = String::from("Hello"); greeting.push_str(", world!"); println!("{}", greeting); // Output: Hello, world! }
We create a String
from a string literal and use push_str
to append more text.
HashMaps: Key-Value Pairs
HashMaps are collections of key-value pairs. They are useful when you need to associate a value with a key. Here’s a basic example:
use std::collections::HashMap; fn main() { let mut scores = HashMap::new(); scores.insert("Alice", 10); scores.insert("Bob", 20); println!("{:?}", scores); }
We use HashMap::new()
to create a new hashmap and insert
to add key-value pairs.
Common Questions and Answers
- What is the difference between a vector and an array in Rust?
Arrays have a fixed size, while vectors can grow or shrink.
- How do I access an element in a vector?
Use indexing, like
numbers[0]
, to access elements. - Can I store different types in a vector?
No, all elements must be of the same type. Consider using an enum for mixed types.
- How do I concatenate strings?
Use
push_str
or the+
operator. - How do I check if a key exists in a hashmap?
Use the
contains_key
method.
Troubleshooting Common Issues
If you encounter a borrow checker error, ensure you’re not violating Rust’s ownership rules.
Remember, practice makes perfect! Try modifying the examples and see what happens. 😊
Practice Exercises
- Create a vector of your favorite numbers and print them.
- Write a function that takes a string and returns its length.
- Build a hashmap to store and retrieve student grades.
For more information, check out the Rust documentation on collections.