Skip to content

Commit 8e0def5

Browse files
authored
Merge pull request sunface#524 from mckzm/mut-slices
Fix Mutable slice content in Collection Types -> Vector -> Slicing
2 parents 9fb6572 + cd1e8a2 commit 8e0def5

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

en/src/collections/vector.md

+7-5
Original file line numberDiff line numberDiff line change
@@ -111,9 +111,9 @@ fn main() {
111111

112112

113113
### Slicing
114-
A Vec can be mutable. On the other hand, slices are read-only objects. To get a slice, use `&`.
114+
Immutable or mutable slices of Vecs can be taken, using `&` or `&mut`, respectively.
115115

116-
In Rust, it’s more common to pass slices as arguments rather than vectors when you just want to provide read access. The same goes for `String` and `&str`.
116+
In Rust, it’s more common to pass immutable slices as arguments rather than vectors when you just want to provide read access, as this is more flexible (no move) and efficient (no copy). The same goes for `String` and `&str`.
117117

118118
5. 🌟🌟
119119
```rust,editable
@@ -129,14 +129,16 @@ fn main() {
129129
130130
assert_eq!(slice1, slice2);
131131
132-
// Slices are read only
132+
// A slice can also be mutable, in which
133+
// case mutating it will mutate its underlying Vec.
133134
// Note: slice and &Vec are different
134135
let vec_ref: &mut Vec<i32> = &mut v;
135136
(*vec_ref).push(4);
136137
let slice3 = &mut v[0..3];
137-
slice3.push(4);
138+
slice3[3] = 42;
138139
139-
assert_eq!(slice3, &[1, 2, 3, 4]);
140+
assert_eq!(slice3, &[1, 2, 3, 42]);
141+
assert_eq!(v, &[1, 2, 3, 42]);
140142
141143
println!("Success!");
142144
}

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)