Common Collection Types in Rust
Rust provides several built-in collection types that are designed to store multiple values. These collections are essential for managing data efficiently and come with various features to suit different use cases. The most common collection types in Rust include Vec
, HashMap
, HashSet
, and BTreeMap
.
1. Vec
(Vector)
A Vec
is a growable array type that allows you to store a variable number of elements. It is one of the most commonly used collection types in Rust.
Example of Using Vec
fn main() {
let mut numbers: Vec<i32> = Vec::new(); // Create a new empty vector
// Adding elements to the vector
numbers.push(1);
numbers.push(2);
numbers.push(3);
// Accessing elements
for number in &numbers {
println!("{}", number);
}
// Removing the last element
numbers.pop();
println!("After popping, the last number is: {:?}", numbers.last());
}
</i32>
Explanation of the Example
- In this example, we create a mutable vector named
numbers
to storei32
values. - We use the
push
method to add elements to the vector and thepop
method to remove the last element. - We iterate over the vector using a for loop and print each number.
- The
last
method is used to access the last element of the vector after popping.
2. HashMap
A HashMap
is a collection that stores key-value pairs. It allows for fast lookups based on keys, making it ideal for scenarios where you need to associate values with unique keys.
Example of Using HashMap
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new(); // Create a new empty HashMap
// Inserting key-value pairs
scores.insert(String::from("Alice"), 50);
scores.insert(String::from("Bob"), 70);
scores.insert(String::from("Charlie"), 90);
// Accessing values
let alice_score = scores.get("Alice").unwrap();
println!("Alice's score: {}", alice_score);
// Iterating over key-value pairs
for (name, score) in &scores {
println!("{}: {}", name, score);
}
}
Explanation of the Example
- In this example, we create a mutable
HashMap
namedscores
to store names as keys and scores as values. - We use the
insert
method to add key-value pairs to the map. - The
get
method retrieves the value associated with a key, and we useunwrap
to handle theOption
returned byget
. - We iterate over the key-value pairs using a for loop and print each name and score.
3. HashSet
A HashSet
is a collection that stores unique values. It is similar to a HashMap
but only stores keys without associated values. It is useful for scenarios where you need to ensure that a value is not duplicated.
Example of Using HashSet
use std::collections::HashSet;
fn main() {
let mut unique_numbers = HashSet::new(); // Create a new empty HashSet
// Inserting values
unique_numbers.insert(1);
unique_numbers.insert(2);
unique_numbers.insert(3);
unique_numbers.insert(2); // Duplicate value, will not be added
// Checking if a value exists
if unique_numbers.contains(&2) {
println!(" 2 is in the set.");
}
// Iterating over the values
for number in &unique_numbers {
println!("{}", number);
}
}
Explanation of the Example
- In this example, we create a mutable
HashSet
namedunique_numbers
to store unique integers. - We use the
insert
method to add values to the set, and attempting to insert a duplicate value does not change the set. - The
contains
method checks if a specific value exists in the set. - We iterate over the values in the set and print each unique number.
4. BTreeMap
A BTreeMap
is a collection that stores key-value pairs in a sorted order. It is similar to a HashMap
but maintains the order of keys, making it useful for scenarios where you need to iterate over keys in a sorted manner.
Example of Using BTreeMap
use std::collections::BTreeMap;
fn main() {
let mut scores = BTreeMap::new(); // Create a new empty BTreeMap
// Inserting key-value pairs
scores.insert("Alice", 50);
scores.insert("Bob", 70);
scores.insert("Charlie", 90);
// Iterating over key-value pairs in sorted order
for (name, score) in &scores {
println!("{}: {}", name, score);
}
}
Explanation of the Example
- In this example, we create a mutable
BTreeMap
namedscores
to store names as keys and scores as values. - We use the
insert
method to add key-value pairs to the map. - When iterating over the key-value pairs, they are printed in sorted order based on the keys.
5. Conclusion
Rust's collection types, such as Vec
, HashMap
, HashSet
, and BTreeMap
, provide powerful tools for managing data. Each collection type has its own strengths and use cases, allowing developers to choose the most appropriate one for their needs. Understanding these collections is essential for effective programming in Rust.