Welcome to Day 8 of your Rust journey! 🎉 Today, we’ll explore Collections in Rust, which are essential for storing multiple values. We'll cover vectors, strings, hash maps, and other collections, and learn how to use them effectively in your programs. Let's get started! 🚀
Congratulations! 🎉 You've taken the first step in your journey to master the 30 Days of Rust programming challenge. In this challenge, you will learn the fundamentals of Rust and how to harness its power to write efficient, fast, and safe code. By the end of this journey, you'll have gained a solid understanding of Rust's core concepts and best practices, helping you become a confident Rustacean. 🦀
Feel free to join the 30 Days of Rust community on Discord, where you can interact with others, ask questions, and share your progress!
In Rust, collections are data structures that hold multiple values. We'll cover:
- Using vectors for dynamic arrays.
- Working with strings for text data.
- Storing key-value pairs with hash maps.
- Exploring other collections available in Rust.
Ensure that you have your Rust environment set up correctly from Day 1. If you haven’t installed Rust yet, please refer to the setup instructions from Day 1.
Vectors are resizable arrays that can hold multiple values of the same type. You can push or pop values dynamically.
Example:
fn main() {
let mut numbers: Vec<i32> = Vec::new();
numbers.push(1);
numbers.push(2);
numbers.push(3);
println!("Numbers: {:?}", numbers);
if let Some(last) = numbers.pop() {
println!("Popped: {}", last);
}
println!("Numbers after pop: {:?}", numbers);
}
Strings in Rust are collections of characters. The String
type is mutable, while &str
is an immutable string slice.
Example:
fn main() {
let mut greeting = String::from("Hello");
greeting.push_str(", world!");
println!("{}", greeting);
let substring = &greeting[0..5]; // "Hello"
println!("Substring: {}", substring);
}
Hash maps store key-value pairs and provide efficient access to data.
Example:
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Alice"), 50);
scores.insert(String::from("Bob"), 60);
scores.insert(String::from("Charlie"), 70);
println!("Scores: {:?}", scores);
let bob_score = scores.get("Bob").unwrap();
println!("Bob's score: {}", bob_score);
}
Rust provides several other useful collections, each designed for specific use cases:
BTreeMap
is an ordered map implementation that stores key-value pairs in a sorted manner. It is useful when you need to maintain order and perform range queries.
Example:
use std::collections::BTreeMap;
fn main() {
let mut scores = BTreeMap::new();
scores.insert("Alice", 50);
scores.insert("Bob", 60);
scores.insert("Charlie", 70);
for (name, score) in &scores {
println!("{}: {}", name, score);
}
}
VecDeque
is a double-ended queue that allows efficient addition and removal of elements from both ends. This is beneficial when you need a queue-like structure but also require quick access to both the front and back.
Example:
use std::collections::VecDeque;
fn main() {
let mut queue: VecDeque<i32> = VecDeque::new();
queue.push_back(1);
queue.push_back(2);
queue.push_front(0);
println!("Queue: {:?}", queue);
if let Some(front) = queue.pop_front() {
println!("Removed from front: {}", front);
}
println!("Queue after pop: {:?}", queue);
}
LinkedList
is a doubly linked list, which allows for efficient insertions and deletions from both ends. It is useful when you need a collection that frequently changes size and requires efficient element removal.
Example:
use std::collections::LinkedList;
fn main() {
let mut list = LinkedList::new();
list.push_back(1);
list.push_back(2);
list.push_front(0);
for value in &list {
println!("{}", value);
}
if let Some(front) = list.pop_front() {
println!("Removed from front: {}", front);
}
println!("List after pop: {:?}", list);
}
Each of these collections has its specific use cases based on performance requirements, such as speed of access and mutability.
Create a Rust program that manages a simple inventory system using collections. Implement the following functionalities:
- Store items in a vector.
- Use a hash map to track the quantities of each item.
- Allow adding, removing, and updating item quantities.
Template:
use std::collections::HashMap;
fn main() {
let mut inventory: Vec<String> = Vec::new();
let mut quantities: HashMap<String, i32> = HashMap::new();
// Add items
inventory.push(String::from("Apples"));
quantities.insert(String::from("Apples"), 10);
// Update quantity
*quantities.get_mut("Apples").unwrap() += 5;
// Remove item
inventory.retain(|item| item != "Bananas");
// Print inventory
for item in &inventory {
let quantity = quantities.get(item).unwrap();
println!("{}: {}", item, quantity);
}
}
✅ Share your solution on GitHub and tag #30DaysOfRust on social media! Let the world see your progress! 🚀
- Create a vector of integers, push values into it, and print the vector.
- Write a program to create a string and append characters to it, displaying the final string.
- Implement a hash map to store names and ages of three people. Print each person's name and age.
- Create a vector of strings, representing fruit names, and sort them in alphabetical order.
- Implement a program that tracks a list of tasks using a vector. Each task should have a description and a boolean indicating if it’s completed.
- Create a hash map to count the occurrences of words in a given sentence. Print each word with its count.
- Use a
VecDeque
to implement a queue for processing tasks. Demonstrate adding and removing tasks from the queue. - Write a program using a
BTreeMap
to store and print a sorted list of student names along with their scores.
- We learned how to work with vectors, strings, and hash maps in Rust.
- We explored other collections available in Rust and their use cases.
- Completed exercises to reinforce our understanding of collections.
🌟 Great job on completing Day 8! Keep practicing, and get ready for Day 9 where we will explore more advanced topics (Error Handling) in Rust!
Thank you for joining Day 8 of the 30 Days of Rust challenge! If you found this helpful, don’t forget to star this repository, share it with your friends, and stay tuned for more exciting lessons ahead!
Stay Connected
📧 Email: Hunterdii
🐦 Twitter: @HetPate94938685
🌐 Website: Working On It(Temporary)