Rust
December 2, 2026 6 min read

Collections in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What Are Collections?

Collections are data structures that store multiple values together.

Unlike arrays, some collections can grow or shrink while the program is running.

Rust provides different collection types for different requirements.


Collection

Purpose

Vector (Vec<T>)

Stores multiple values in a sequence

HashMap (HashMap<K, V>)

Stores data as key-value pairs

HashSet (HashSet<T>)

Stores unique values

2. Understanding Vectors (Vec<T>)

A Vector is a collection that stores multiple values of the same data type.

Unlike arrays, vectors can grow or shrink dynamically.

Creating a Vector

Syntax:

let numbers: Vec<i32> = Vec::new();

Example:

fn main() {
let mut numbers: Vec<i32> = Vec::new();

numbers.push(10);
numbers.push(20);
numbers.push(30);

println!("{:?}", numbers);
}

Output:

[10, 20, 30]

Explanation:

  1. Vec<i32> creates a vector of integers.
  2. Vec::new() creates an empty vector.
  3. mut allows us to modify the vector.
  4. push() adds an element.

Creating a Vector Using vec!

Rust also provides the vec! macro.

fn main() {
let numbers = vec![10, 20, 30, 40];

println!("{:?}", numbers);
}

Output:

[10, 20, 30, 40]

Adding Elements Using push()

fn main() {
let mut fruits = vec!["Apple", "Banana"];

fruits.push("Mango");
fruits.push("Orange");

println!("{:?}", fruits);
}

Output:

["Apple", "Banana", "Mango", "Orange"]

Removing Elements Using pop()

The pop() method removes and returns the last element.

fn main() {
let mut numbers = vec![10, 20, 30, 40];

let removed = numbers.pop();

println!("Removed: {:?}", removed);
println!("Remaining: {:?}", numbers);
}

Output:

Removed: Some(40)
Remaining: [10, 20, 30]

Notice that pop() returns an Option<T> because the vector may be empty.

Accessing Vector Elements

There are two common ways to access vector elements.

Method 1: Using Index

fn main() {
let numbers = vec![10, 20, 30];

println!("{}", numbers[0]);
}

Output:

10

Remember: Vector indexing starts from 0.


Index

Value

0

10

1

20

2

30

Accessing an invalid index using [] causes a panic.

Method 2: Using get()

fn main() {
let numbers = vec![10, 20, 30];

match numbers.get(5) {
Some(value) => println!("Value: {}", value),
None => println!("Index not found"),
}
}

Output:

Index not found

The get() method returns Option<&T>, so it allows you to handle an invalid index safely.

Updating Vector Elements

fn main() {
let mut numbers = vec![10, 20, 30];

numbers[1] = 100;

println!("{:?}", numbers);
}

Output:

[10, 100, 30]

Finding the Length of a Vector

fn main() {
let numbers = vec![10, 20, 30, 40];

println!("Length: {}", numbers.len());
}

Output:

Length: 4

Iterating Through a Vector

You can use a for loop to access every element.

fn main() {
let numbers = vec![10, 20, 30];

for number in &numbers {
println!("{}", number);
}
}

Output:

10
20
30

Here, &numbers borrows the vector, so the vector remains available after the loop.

Iterating and Updating Elements

fn main() {
let mut numbers = vec![10, 20, 30];

for number in &mut numbers {
*number += 5;
}

println!("{:?}", numbers);
}

Output:

[15, 25, 35]

The * dereferences the mutable reference so we can update the value.

3. Understanding HashMap (HashMap<K, V>)

A HashMap stores information as key-value pairs.

For example:


Key

Value

Name

Hemant

Course

Rust

Age

32

In a HashMap:

  1. Every key is unique.
  2. A key is used to access its corresponding value.
  3. Values can be of the same type.

Creating a HashMap

First, import HashMap:

use std::collections::HashMap;

Example:

use std::collections::HashMap;

fn main() {
let mut student = HashMap::new();

student.insert("name", "Hemant");
student.insert("course", "Rust");
student.insert("city", "Almora");

println!("{:?}", student);
}

The order of displayed entries is not guaranteed.

Accessing Values Using get()

use std::collections::HashMap;

fn main() {
let mut student = HashMap::new();

student.insert("name", "Hemant");
student.insert("course", "Rust");

let name = student.get("name");

println!("{:?}", name);
}

Output:

Some("Hemant")

get() returns an Option<&V> because the requested key may not exist.

Handling Missing Keys

use std::collections::HashMap;

fn main() {
let mut student = HashMap::new();

student.insert("name", "Hemant");

match student.get("age") {
Some(value) => println!("Age: {}", value),
None => println!("Age not found"),
}
}

Output:

Age not found

Updating Values

You can insert a value using an existing key to replace its previous value.

use std::collections::HashMap;

fn main() {
let mut student = HashMap::new();

student.insert("course", "Python");
student.insert("course", "Rust");

println!("{:?}", student.get("course"));
}

Output:

Some("Rust")

Removing Elements

Use remove() to remove a key and its associated value.

use std::collections::HashMap;

fn main() {
let mut student = HashMap::new();

student.insert("name", "Hemant");
student.insert("course", "Rust");

student.remove("course");

println!("{:?}", student);
}

Checking Whether a Key Exists

Use contains_key().

use std::collections::HashMap;

fn main() {
let mut student = HashMap::new();

student.insert("name", "Hemant");

println!("{}", student.contains_key("name"));
println!("{}", student.contains_key("age"));
}

Output:

true
false

Iterating Through a HashMap

use std::collections::HashMap;

fn main() {
let mut student = HashMap::new();

student.insert("name", "Hemant");
student.insert("course", "Rust");

for (key, value) in &student {
println!("{}: {}", key, value);
}
}

The order of entries is not guaranteed.

4. Understanding HashSet (HashSet<T>)

A HashSet is a collection that stores unique values.

It does not allow duplicate elements.

Example:

use std::collections::HashSet;

fn main() {
let mut numbers = HashSet::new();

numbers.insert(10);
numbers.insert(20);
numbers.insert(30);
numbers.insert(10);

println!("{:?}", numbers);
}

The set contains only:

{10, 20, 30}

The order is not guaranteed.

Notice that 10 was inserted twice, but the HashSet stores it only once.

Checking Whether a Value Exists

Use contains().

use std::collections::HashSet;

fn main() {
let mut numbers = HashSet::new();

numbers.insert(10);
numbers.insert(20);

println!("{}", numbers.contains(&10));
println!("{}", numbers.contains(&50));
}

Output:

true
false

Removing Values

use std::collections::HashSet;

fn main() {
let mut numbers = HashSet::new();

numbers.insert(10);
numbers.insert(20);
numbers.insert(30);

numbers.remove(&20);

println!("{:?}", numbers);
}

The set now contains 10 and 30.

Set Operations

Rust supports common mathematical set operations.

Consider two sets:

use std::collections::HashSet;

fn main() {
let a: HashSet<i32> = [1, 2, 3].into_iter().collect();
let b: HashSet<i32> = [3, 4, 5].into_iter().collect();

println!("Union: {:?}", a.union(&b).collect::<Vec<_>>());
println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<_>>());
println!("Difference: {:?}", a.difference(&b).collect::<Vec<_>>());
}

Meaning:


Operation

Result

Union

All unique elements from both sets

Intersection

Elements common to both sets

Difference

Elements in the first set but not the second

Expected values:

  1. Union: 1, 2, 3, 4, 5
  2. Intersection: 3
  3. Difference: 1, 2

The displayed order is not guaranteed.

5. Difference Between Vector, HashMap, and HashSet


Feature

Vector

HashMap

HashSet

Stores

Values

Key-value pairs

Unique values

Duplicates

Allowed

Keys are unique

Not allowed

Access

Index

Key

Membership check

Order

Insertion order

Not guaranteed

Not guaranteed

Example

Student names

Student ID and name

Unique student IDs

6. When Should You Use Each Collection?

Use Vector when:

  1. You need a list of student names.
  2. You want to store product prices.
  3. You need to maintain a sequence of values.

Use HashMap when:

  1. You want to store student ID and student name.
  2. You want to store product ID and price.
  3. You need to access information using a key.

Use HashSet when:

  1. You want to store unique email addresses.
  2. You want to avoid duplicate student IDs.
  3. You need to check whether an item already exists.