Rust Collections: A Comprehensive Guide

What are Rust Collections?

Rust collections are data structures that store multiple values in a sequence or group. Unlike arrays or tuples, collections are allocated on the heap, allowing their size to grow or shrink dynamically at runtime.

Choosing the Right Collection

With so many collection types available, selecting the right one can be daunting. Each collection has its strengths and weaknesses, and understanding these differences is crucial for optimal performance.

  • Sequence: Vec, VecDeque, LinkedList
  • Maps: HashMap, BTreeMap
  • Sets: HashSet, BTreeSet
  • Misc: BinaryHeap

Vectors: The Default Choice

Vectors are the most commonly used collection type in Rust. They offer a resizable array-like data structure, making them perfect for storing items of the same type.

Creating a Vector

let mut my_vector = Vec::new();
my_vector.push(1);
my_vector.push(2);

Accessing Elements

let second_element = &my_vector[1];
let second_element = my_vector.get(1).unwrap();

Iterating Over Elements

for element in &my_vector {
    println!("{}", element);
}

Strings: A Special Case

Strings in Rust are stored as a collection of UTF-8 encoded bytes. They’re essentially a vector of characters, but with some additional functionality.

Creating a String

let my_string = String::new();
let my_string = "Hello".to_string();

Concatenating Strings

let mut my_string = String::from("Hello");
my_string.push_str(" World");
let my_string = "Hello".to_string() + " World";

Hash Maps: Key-Value Pairs

Hash maps store data in key-value pairs, making them perfect for caching or mapping values to keys.

Creating a Hash Map

let mut my_hash_map = HashMap::new();
my_hash_map.insert("key", "value");

Accessing Values

let value = my_hash_map.get("key").unwrap();

Leave a Reply

Your email address will not be published. Required fields are marked *