Skip to content

Latest commit

 

History

History
104 lines (73 loc) · 3.86 KB

10. collections_vectors_strings_and_hashmaps.md

File metadata and controls

104 lines (73 loc) · 3.86 KB

10. Collections: Vectors, Strings, and HashMaps

Introduction to Collections in Rust

Collections are like your toolbox in Rust programming. Just like a toolbox contains various tools for different tasks, Rust collections provide different data structures to store and manage your data efficiently.

Vectors: Dynamic Arrays

Vectors are your go-to choice when you need a flexible container that can grow or shrink as needed. They're like magic bags that can hold anything you throw into them, whether it's numbers, strings, or even your favorite snacks!

// Creating a vector of numbers
let numbers = vec![1, 2, 3, 4, 5];

// Modifying a vector
let mut shopping_list = Vec::new();
shopping_list.push("apples");
shopping_list.push("bananas");

Strings: Text Adventures in Rust

Strings in Rust are not just sequences of characters; they're like little universes of text waiting to be explored. Whether you're concatenating them, slicing them, or searching for patterns within them, Rust strings have got you covered.

// Creating a string
let message = String::from("Hello, Rust!");

// Concatenating strings
let greeting = "Hello".to_string() + ", " + "Rust!";

// Finding substrings
let url = "https://example.com";
if url.starts_with("https://") {
    println!("Secure connection!");
}

HashMaps: Your Treasure Map

HashMaps are like treasure maps in Rust, helping you navigate through a sea of keys and values to find the hidden treasures you seek. Whether you're storing user preferences, caching results, or building a dictionary, HashMaps will guide you to success.

// Creating a HashMap
use std::collections::HashMap;
let mut scores = HashMap::new();

// Inserting and accessing values
scores.insert("Alice", 42);
scores.insert("Bob", 37);

// Retrieving a value
if let Some(score) = scores.get("Alice") {
    println!("Alice's score: {}", score);
}

Operations and Methods for Working with Collections

Collections come with a set of handy operations and methods to make your life easier. Whether you're sorting, cloning, slicing, or searching, Rust collections have everything you need to get the job done efficiently.

// Sorting a vector
let mut numbers = vec![5, 2, 3, 1, 4];
numbers.sort();

// Cloning a string
let original = String::from("Hello");
let cloned = original.clone();

// Searching in a vector
if numbers.contains(&3) {
    println!("Found the number 3!");
}

Iterating Over and Manipulating Collections

Iterators are your trusty companions when it comes to traversing and transforming collections in Rust. Whether you're mapping, filtering, or chaining operations, iterators help you navigate through your data with ease.

// Iterating over a vector
let numbers = vec![1, 2, 3, 4, 5];
for num in &numbers {
    println!("{}", num);
}

// Mapping over a vector
let doubled: Vec<_> = numbers.iter().map(|x| x * 2).collect();

Best Practices

  • Choose the right collection for the job: vectors for dynamic arrays, strings for text data, and HashMaps for key-value pairs.
  • Use collection methods and operations to manipulate your data efficiently and expressively.
  • Embrace iterators to iterate over and transform your collections with elegance and simplicity.

Real-World Example

Imagine you're building a recipe management app in Rust. You use vectors to store ingredients, strings to represent recipe names and instructions, and HashMaps to store user preferences and ratings for each recipe. By leveraging Rust collections effectively, you create a user-friendly app that helps people cook delicious meals with ease.

Conclusion

Collections are like Swiss Army knives in Rust programming, offering a wide range of tools to handle different data scenarios. By mastering vectors, strings, and HashMaps, you'll become a proficient Rust programmer ready to tackle any data-related challenge with confidence and flair.