capypad
0 day streak
rust / beginner
Snippet

Working with Vectors

Vectors (Vec<T>) are growable arrays provided by the standard library, unlike fixed-size arrays. They support dynamic resizing with push() and offer powerful iteration methods like map(), filter(), and sum(). The iter() method creates an iterator for safe read-only access.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() {
let mut numbers: Vec<i32> = Vec::new();
numbers.push(1);
numbers.push(2);
numbers.push(3);
let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect();
let sum: i32 = numbers.iter().sum();
if let Some(first) = numbers.first() {
println!("First number: {}", first);
}
for (index, num) in numbers.iter().enumerate() {
println!("Index {}: {}", index, num);
}
}
Breakdown
1
let mut numbers: Vec<i32> = Vec::new();
Creates a new empty vector with explicit type annotation
2
.iter().map(|x| x * 2).collect()
Chains iterator methods to transform and collect results
3
numbers.first()
Returns Some(value) or None if vector is empty