In this tutorial, you’ll learn how to work with dynamic arrays using Rust vectors.
What is a Vector? #
A vector is a growable, heap-allocated array. Unlike fixed-size arrays ([T; N]), vectors can:
- Change size at runtime
- Store multiple elements of the same type
T - Provide convenient methods for adding/removing elements
Think of it like a resizable list 📋.
Creating Vectors #
There are several ways to create vectors. For example:
fn main() {
// Empty vector, specify type
let v: Vec<i32> = Vec::new();
// With the vec! macro
let v2 = vec![1, 2, 3];
// Mutable vector, so we can push elements
let mut v3 = Vec::new();
v3.push(10);
v3.push(20);
v3.push(30);
println!("{:?}", v3); // [10, 20, 30]
}Code language: Rust (rust)Output:
[10, 20, 30]Code language: Rust (rust)Accessing Elements #
You can get elements by indexing or with .get():
fn main() {
let v = vec![10, 20, 30, 40];
// Direct indexing (may panic if out of bounds)
println!("First: {}", v[0]);
// Using .get() returns Option<&T>
match v.get(2) {
Some(value) => println!("Third element is {}", value),
None => println!("No element at index 2"),
}
}
Code language: Rust (rust)Output:
First: 10
Third element is 30Code language: Rust (rust)Use .get() when you want safe access that won’t panic.
Iterating Over Vectors #
fn main() {
let v = vec![100, 200, 300];
// Borrowed iteration
for x in &v {
println!("Value: {}", x);
}
// Mutable iteration
let mut v2 = vec![1, 2, 3];
for x in &mut v2 {
*x *= 2; // modify in place
}
println!("{:?}", v2); // [2, 4, 6]
// Into iteration (takes ownership)
for x in v {
println!("Owned value: {}", x);
}
}Code language: Rust (rust)Output:
Value: 100
Value: 200
Value: 300
[2, 4, 6]
Owned value: 100
Owned value: 200
Owned value: 300Code language: Rust (rust)Removing Elements #
Vectors have methods like pop(), remove(), and clear():
fn main() {
let mut v = vec![1, 2, 3, 4];
v.pop(); // removes last element
println!("{:?}", v); // [1, 2, 3]
v.remove(1); // removes element at index 1
println!("{:?}", v); // [1, 3]
v.clear(); // removes all elements
println!("{:?}", v); // []
}
Code language: Rust (rust)Output:
[1, 2, 3]
[1, 3]
[]Code language: Rust (rust)Storing Multiple Types #
Vectors must store the same type, but you can use enums for mixed data:
enum Value {
Int(i32),
Float(f64),
Text(String),
}
fn main() {
let v = vec![
Value::Int(10),
Value::Float(3.14),
Value::Text(String::from("Hello")),
];
for item in v {
match item {
Value::Int(i) => println!("Integer: {}", i),
Value::Float(f) => println!("Float: {}", f),
Value::Text(s) => println!("String: {}", s),
}
}
}
Code language: Rust (rust)Output:
Integer: 10
Float: 3.14
String: HelloCode language: Rust (rust)Summary #
Vec<T>= growable, heap-allocated array.- Use
vec![...]macro for easy initialization. - Access elements with
[]or.get(). - Iterate with
for, either by reference, mutable, or by value. - Modify with
.push(),.pop(),.remove(),.clear(). - For mixed types, use
enuminside a vector.
Was this Helpful ?