From fd0c2c50c1a145e746735af7751919814f22a52a Mon Sep 17 00:00:00 2001 From: mckzm <134839822+mckzm@users.noreply.github.com> Date: Sat, 15 Jun 2024 13:39:12 +0900 Subject: [PATCH] update vector/slicing exercise solution w/ mutable slice material --- solutions/collections/Vector.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/solutions/collections/Vector.md b/solutions/collections/Vector.md index 7581a80..68edfba 100644 --- a/solutions/collections/Vector.md +++ b/solutions/collections/Vector.md @@ -156,21 +156,24 @@ fn main() { let mut v = vec![1, 2, 3]; let slice1 = &v[..]; - // out of bounds will cause a panic + // Out of bounds will cause a panic // You must use `v.len` here - let slice2 = &v[0..v.len()]; + let slice2 = &v[0..3]; assert_eq!(slice1, slice2); - // slice are read only + // A slice can also be mutable, in which + // case mutating it will also mutate its underlying Vec // Note: slice and &Vec are different let vec_ref: &mut Vec = &mut v; (*vec_ref).push(4); - let slice3 = &mut v[0..]; + let slice3 = &mut v[0..4]; + slice3[3] = 42; - assert_eq!(slice3, &[1, 2, 3, 4]); + assert_eq!(slice3, &[1, 2, 3, 42]); + assert_eq!(v, &[1, 2, 3, 42]); - println!("Success!") + println!("Success!"); } ```