Now that you have an overview of slices, let's make it a little bit more challenging. In this problem, you will implement a function that updates specific elements of a mutable slice.
Write a function update_slice(slice: &mut [i32], indices: &[usize], value: i32)
that updates specific elements of a mutable slice. The function should:
slice
) as the first argument.indices
) that specify which elements of the mutable slice to update.value
.The function should handle the following:
indices
is out of bounds for the slice
, the function should skip it without causing a panic.indices
slice do not cause runtime errors.let mut data = vec![1, 2, 3, 4, 5];
update_slice(&mut data, &[1, 3, 4], 7);
assert_eq!(data, vec![1, 7, 3, 7, 7]);
let mut data = vec![10, 20, 30];
update_slice(&mut data, &[2, 5], 100); // Index 5 is out of bounds
assert_eq!(data, vec![10, 20, 100]);
If you're having trouble, consider these hints:
.get_mut(index)
method to safely access a mutable reference to an element at a given index. This avoids panics for out-of-bound accesses.for
loop is useful for iterating through the indices
slice.