Skip to content

Commit fd0c2c5

Browse files
authored
update vector/slicing exercise solution w/ mutable slice material
1 parent c4804e3 commit fd0c2c5

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

solutions/collections/Vector.md

+9-6
Original file line numberDiff line numberDiff line change
@@ -156,21 +156,24 @@ fn main() {
156156
let mut v = vec![1, 2, 3];
157157

158158
let slice1 = &v[..];
159-
// out of bounds will cause a panic
159+
// Out of bounds will cause a panic
160160
// You must use `v.len` here
161-
let slice2 = &v[0..v.len()];
161+
let slice2 = &v[0..3];
162162

163163
assert_eq!(slice1, slice2);
164164

165-
// slice are read only
165+
// A slice can also be mutable, in which
166+
// case mutating it will also mutate its underlying Vec
166167
// Note: slice and &Vec are different
167168
let vec_ref: &mut Vec<i32> = &mut v;
168169
(*vec_ref).push(4);
169-
let slice3 = &mut v[0..];
170+
let slice3 = &mut v[0..4];
171+
slice3[3] = 42;
170172

171-
assert_eq!(slice3, &[1, 2, 3, 4]);
173+
assert_eq!(slice3, &[1, 2, 3, 42]);
174+
assert_eq!(v, &[1, 2, 3, 42]);
172175

173-
println!("Success!")
176+
println!("Success!");
174177
}
175178
```
176179

0 commit comments

Comments
 (0)