Sub topic 3
Mutable Slices and Splitting a Buffer
Assume basic Rust syntax, ownership, borrowing, arrays, and Vec<T>. A mutable slice, &mut [T], is a borrowed, writable view into contiguous elements. It does not own or copy the data.
Mutable slices and splitting a buffer
Rust allows only one mutable borrow of a value at a time. This prevents conflicting writes. split_at_mut safely creates two non-overlapping mutable slices, so both can be used together.
fn main() {
let mut data = [1, 2, 3, 4, 5, 6];
let (left, right) = data.split_at_mut(3);
left[0] = 10;
right[2] = 60;
println!("{data:?}");
}Useful slice methods and iterators
iter visits elements without modifying them. windows yields overlapping slices. chunks yields non-overlapping slices. split_at is the immutable counterpart to split_at_mut. binary_search requires sorted data.
fn main() {
let data = [1, 2, 3, 4, 5];
let sums: Vec<i32> = data.windows(2).map(|w| w[0] + w[1]).collect();
println!("{sums:?}");
for chunk in data.chunks(2) {
println!("{chunk:?}");
}
println!("{:?}", data.binary_search(&4));
}Matching on slice patterns
Slice patterns match length and positions:
fn describe(values: &[i32]) -> &'static str {
match values {
[] => "empty",
[one] => "one",
[first, .., last] if first == last => "matching ends",
[_, ..] => "several",
}
}Fat pointers and unsized types
[T] is an unsized type because its length is known only at runtime. A reference to it is a fat pointer containing a data address and a length. &str has the same shape, but its length counts UTF-8 bytes.
Converting to owned data
Use to_vec to copy a slice into an owned Vec<T>. Use into_boxed_slice when an owned, fixed-length allocation is useful.
fn main() {
let slice = &[1, 2, 3][..];
let vector = slice.to_vec();
let boxed: Box<[i32]> = vector.into_boxed_slice();
println!("{boxed:?}");
}Exercise
Why can two mutable slices from splitatmut be used at the same time?
Show answer
They cover disjoint ranges, so writes through one cannot conflict with writes through the other.