You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Rust's standard library provides powerful collection types that store data on the heap, along with an iterator system that enables functional-style data processing with zero-cost abstractions.
A Vec<T> is a growable, heap-allocated array:
// Creating vectors
let mut v: Vec<i32> = Vec::new();
let v2 = vec![1, 2, 3]; // macro shorthand
// Adding elements
v.push(1);
v.push(2);
v.push(3);
// Accessing elements
let third = &v[2]; // panics if out of bounds
let third = v.get(2); // returns Option<&i32>
| Method | Description |
|---|---|
push(value) | Add an element to the end |
pop() | Remove and return the last element |
len() | Number of elements |
is_empty() | Check if empty |
contains(&value) | Check if a value exists |
sort() | Sort in place |
dedup() | Remove consecutive duplicates |
retain(|x| pred) | Keep only elements matching a predicate |
iter() | Create an iterator |
let v = vec![1, 2, 3];
// Immutable iteration
for val in &v {
println!("{val}");
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.