From c9bb868bdcd4ba96e7f517e9c768dbf5b303dfc2 Mon Sep 17 00:00:00 2001 From: Fredrik Klingenberg Date: Sun, 19 Nov 2023 11:04:20 +0100 Subject: [PATCH] feat: showcasing example of adding and holding a reference to a vector Signed-off-by: Fredrik Klingenberg --- projects/collections/src/main.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/projects/collections/src/main.rs b/projects/collections/src/main.rs index 6793685..365d832 100644 --- a/projects/collections/src/main.rs +++ b/projects/collections/src/main.rs @@ -9,4 +9,15 @@ fn main() { v.push(6); v.push(7); v.push(8); + + let e = vec![1, 2, 3, 4, 5]; + let third = &e[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 + match third { + Some(third) => println!("The third element is {}", third), + None => println!("There is no third element"), + } }