Sling Academy
Home/Rust/Rust - Using generic collections like `Vec<T>` and `HashMap<K, V>`

Rust - Using generic collections like `Vec` and `HashMap`

Last updated: January 04, 2025

Introduction to Generic Collections in Rust

Generic collections are a powerful feature in Rust that allow developers to create flexible and reusable code. Two of the most commonly used generic collections in Rust are Vec<T> and HashMap<K, V>. These collections enable developers to store data in a structured way, leveraging the power of Rust's type system and memory safety without compromising on performance.

Understanding Vec<T> in Rust

Vec<T> is a dynamic array provided by Rust's standard library, where T stands for any type. It is akin to Java's ArrayList or Python's list. The power of Vec<T> lies in its ability to dynamically allocate memory, making it possible to grow and shrink as needed.

fn main() {
    let mut numbers: Vec<i32> = Vec::new();
    numbers.push(5);
    numbers.push(10);
    numbers.push(15);
    println!("Numbers: {:?}", numbers);
}

In the example above, a Vec<i32> is created, which stores integers (i32). The vector starts empty, and elements are added using the push method. Finally, we print the contents of the vector.

Common Operations on Vectors

Vectors support a variety of operations that make them versatile for different use cases:

  • Accessing Elements: Use indexing similar to an array.
  • Iterating Over Elements: Via a for loop.
  • Removing Elements: Use pop to remove the last element.
  • Finding Length: Use the len method to get the number of elements.

Diving into HashMap<K, V>

HashMap<K, V> is Rust's construct for a key-value storage, akin to dictionaries in Python or hash tables in other languages. The K denotes the key type, and V represents the value type.

use std::collections::HashMap;

fn main() {
    let mut book_reviews: HashMap<String, String> = HashMap::new();
    book_reviews.insert(String::from("Rust Book"), String::from("Excellent"));
    book_reviews.insert(String::from("Programming 101"), String::from("Good"));

    println!("Reviews: {:?}", book_reviews);
}

In the example above, a HashMap<String, String> is created to store book reviews, with book titles as keys and review descriptions as values. We insert new entries using the insert method.

Common Operations on HashMaps

HashMaps provide various operations tailored for efficient key-value data manipulation:

  • Accessing Values: Use the get method which returns an Option.
  • Iterating Over Entries: Via iterators for keys and values.
  • Removing Entries: Use the remove method.
  • Checking for a Key: Use contains_key.

Conclusion

Generic collections such as Vec<T> and HashMap<K, V> are integral parts of Rust programming. They provide flexibility while ensuring that type-safety and performance are not compromised. These collections allow developers to focus on crafting efficient algorithms and building robust software, while Rust handles the complexities of memory management and thread safety.

Next Article: Rust - Handling generic errors: `Result` with trait-based error types

Previous Article: Why Rust requires explicit trait bounds instead of inheritance

Series: Generic types in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior