mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 04:29:41 +00:00
Merge pull request #524 from mckzm/mut-slices
Fix Mutable slice content in Collection Types -> Vector -> Slicing
This commit is contained in:
@ -111,9 +111,9 @@ fn main() {
|
||||
|
||||
|
||||
### Slicing
|
||||
A Vec can be mutable. On the other hand, slices are read-only objects. To get a slice, use `&`.
|
||||
Immutable or mutable slices of Vecs can be taken, using `&` or `&mut`, respectively.
|
||||
|
||||
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`.
|
||||
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`.
|
||||
|
||||
5. 🌟🌟
|
||||
```rust,editable
|
||||
@ -129,14 +129,16 @@ fn main() {
|
||||
|
||||
assert_eq!(slice1, slice2);
|
||||
|
||||
// Slices are read only
|
||||
// A slice can also be mutable, in which
|
||||
// case mutating it will mutate its underlying Vec.
|
||||
// Note: slice and &Vec are different
|
||||
let vec_ref: &mut Vec<i32> = &mut v;
|
||||
(*vec_ref).push(4);
|
||||
let slice3 = &mut v[0..3];
|
||||
slice3.push(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!");
|
||||
}
|
||||
|
@ -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<i32> = &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!");
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user