rust / beginner
Snippet
Working with Vectors
Vectors are dynamic arrays provided by the standard library. You can create them with Vec::new() and push elements, or use the vec! macro for quick initialization. Access elements safely with get() which returns Option, or use indexing for direct access.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let mut numbers: Vec<i32> = Vec::new();numbers.push(1);numbers.push(2);numbers.push(3);let scores = vec![10, 20, 30, 40];println!("First: {}", scores[0]);for num in &scores {println!("Number: {}", num);}if let Some(third) = scores.get(2) {println!("Third element: {}", third);}
Breakdown
1
let mut numbers: Vec<i32> = Vec::new();
Creates a new empty vector that will hold i32 values
2
numbers.push(1);
Appends an element to the end of the vector
3
let scores = vec![10, 20, 30, 40];
Uses vec! macro to create and initialize a vector
4
scores[0]
Direct indexing access to first element
5
scores.get(2)
Safe access returning Option<i32>, None if out of bounds
6
for num in &scores { ... }
Iterates over references to each element