capypad
0 day streak
rust / beginner
Snippet

Creating and Using Vectors in Rust

Vectors are growable arrays stored on the heap. The vec! macro creates a vector with initial values. You can transform vectors using iterator methods like map() and filter(), which are lazy and only execute when collected().

snippet.rs
rust
1
2
3
4
5
6
7
fn main() {
let numbers: Vec<i32> = vec![1, 2, 3];
let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect();
let filtered: Vec<i32> = numbers.iter().filter(|x| x % 3 == 0).collect();
println!("Doubled: {:?}", doubled);
println!("Divisible by 3: {:?}", filtered);
}
Breakdown
1
let numbers: Vec<i32> = vec![1, 2, 3];
Creates a vector of integers using the vec! macro
2
.iter().map(|x| x * 2)
Iterates over elements and transforms each by multiplying by 2
3
.collect()
Executes the lazy iterator chain and collects results into a new vector