capypad
0 day streak
rust / beginner
Snippet

Vector Basics: Creating and Iterating

Vectors are growable arrays provided by the standard library. They store elements of the same type contiguously in memory. You can create them with Vec::new() or the convenient vec! macro. Use get() for safe index access that returns an Option, avoiding panics from out-of-bounds access.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn main() {
// Creating a new vector
let mut numbers: Vec<i32> = Vec::new();
// Adding elements with push
numbers.push(10);
numbers.push(20);
numbers.push(30);
// Using vec! macro for quick creation
let fruits = vec!["apple", "banana", "orange"];
// Iterating with for loop
for fruit in &fruits {
println!("Fruit: {}", fruit);
}
// Getting value at index with get
if let Some(second) = fruits.get(1) {
println!("Second fruit: {}", second);
}
// Check vector length
println!("Number of fruits: {}", fruits.len());
}
Breakdown
1
let mut numbers: Vec<i32> = Vec::new();
Creates an empty mutable vector of i32 values
2
numbers.push(10);
Appends an element to the end of the vector
3
let fruits = vec!["apple", "banana"];
Macro creates and initializes a vector with values
4
fruits.get(1)
Safe index access returning Option<&str>