In this challenge, you'll explore how to work with mutable slices in Rust. A mutable slice, &mut [T]
, allows you to modify the elements of a collection directly and efficiently without creating a new collection.
Slices are a fundamental part of Rust, providing a view into contiguous sequences of elements such as arrays or vectors. When working with slices, you can iterate over and manipulate the elements dynamically.
Write a function modify_elements(slice: &mut [i32])
that modifies the elements of a mutable slice of integers in the following way:
let mut numbers = [1, 2, 3, 4, 5];
modify_elements(&mut numbers);
// Odd numbers reduced by 1
// Even numbers doubled
assert_eq!(numbers, [0, 4, 2, 8, 4]);
let mut numbers = [10, 15, 20];
modify_elements(&mut numbers);
// 10 -> 20, 15 -> 14, 20 -> 40
assert_eq!(numbers, [20, 14, 40]);
If you're stuck, here are some hints to help you:
.iter_mut()
method to traverse the slice by mutable reference.num % 2 == 0
.*
) to update the value pointed to by the mutable reference.for
loop with mutable references for concise modification.