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
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 vectorlet mut numbers: Vec<i32> = Vec::new();// Adding elements with pushnumbers.push(10);numbers.push(20);numbers.push(30);// Using vec! macro for quick creationlet fruits = vec!["apple", "banana", "orange"];// Iterating with for loopfor fruit in &fruits {println!("Fruit: {}", fruit);}// Getting value at index with getif let Some(second) = fruits.get(1) {println!("Second fruit: {}", second);}// Check vector lengthprintln!("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>