Skip to content

Commit

Permalink
feat: iterating over vector values
Browse files Browse the repository at this point in the history
Signed-off-by: Fredrik Klingenberg <[email protected]>
  • Loading branch information
fredrkl committed Nov 19, 2023
1 parent c9bb868 commit a67fcb1
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions projects/collections/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,27 @@ fn main() {
v.push(7);
v.push(8);

let e = vec![1, 2, 3, 4, 5];
let third = &e[2];
let v = vec![1, 2, 3, 4, 5];
let third = &v[2];
// e.push(6); // Changing e to mutable (mut) and uncommenting this line will cause an error because we are trying to borrow a mutable reference to e while we have an immutable reference to e
println!("The third element is {}", third);

let third = e.get(2); // The reson why this is option is because it might not exist, the index might be out of bounds
let third = v.get(2); // The reson why this is option is because it might not exist, the index might be out of bounds
match third {
Some(third) => println!("The third element is {}", third),
None => println!("There is no third element"),
}

for i in &v {
println!("{i}")
}

let mut v = vec![100, 32, 57];
for i in &mut v {
*i += 50; // Dereference i to get the value it refers to, then add 50 to that value
}

for i in &v {
println!("{i}")
}
}

0 comments on commit a67fcb1

Please sign in to comment.