capypad
0 day streak
rust / beginner
Snippet

Working with Vectors

Vectors are dynamic, 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. The `get()` method returns an `Option` for safe access, while indexing with `[]` would panic on 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
fn main() {
let mut vec = Vec::new();
vec.push(10);
vec.push(20);
vec.push(30);
println!("Vector: {:?}", vec);
 
let vec2 = vec![1, 2, 3];
println!("Vector with macro: {:?}", vec2);
 
if let Some(val) = vec.get(1) {
println!("Value at index 1: {}", val);
}
 
for item in &vec {
println!("Item: {}", item);
}
}
Breakdown
1
let mut vec = Vec::new();
Creates an empty vector that can grow dynamically.
2
vec.push(10);
Adds elements to the end of the vector.
3
vec.get(1)
Safely accesses element at index 1, returning `Option<&T>`.
4
for item in &vec
Iterates over references to each element without consuming the vector.