From a67fcb1509e8b11157e1e0500391312f572653b0 Mon Sep 17 00:00:00 2001 From: Fredrik Klingenberg Date: Sun, 19 Nov 2023 11:13:23 +0100 Subject: [PATCH] feat: iterating over vector values Signed-off-by: Fredrik Klingenberg --- projects/collections/src/main.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/projects/collections/src/main.rs b/projects/collections/src/main.rs index 365d832..0db21b0 100644 --- a/projects/collections/src/main.rs +++ b/projects/collections/src/main.rs @@ -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}") + } }