Mastering Mutable References in Rust
Mutable references are a cornerstone of Rust's memory safety guarantees, allowing you to modify data in place without risking data races. Understanding how to create and use them correctly is crucial for writing efficient and safe Rust code. This challenge will test your ability to create and utilize mutable references to modify data within a simple data structure.
Problem Description
Your task is to implement a function that takes ownership of a Vec<i32> (a growable array of integers) and modifies its elements using a mutable reference. Specifically, you need to:
- Create a mutable reference to the input
Vec<i32>. - Iterate through the elements of the vector using this mutable reference.
- Modify each element by adding 5 to its current value.
- Return the modified
Vec<i32>.
This exercise will help you solidify your understanding of borrowing, mutability, and how to manipulate data structures owned by a function.
Examples
Example 1:
Input: vec![1, 2, 3, 4]
Output: vec![6, 7, 8, 9]
Explanation: The function receives `vec![1, 2, 3, 4]`. Each element is then incremented by 5: 1+5=6, 2+5=7, 3+5=8, 4+5=9.
Example 2:
Input: vec![-10, 0, 10]
Output: vec![-5, 5, 15]
Explanation: The function receives `vec![-10, 0, 10]`. Each element is incremented by 5: -10+5=-5, 0+5=5, 10+5=15.
Example 3:
Input: vec![]
Output: vec![]
Explanation: An empty vector should be handled gracefully, resulting in an empty vector.
Constraints
- The input will always be a
Vec<i32>. - The values within the vector can range from
i32::MINtoi32::MAX. Ensure that adding 5 does not cause overflow (for typicali32ranges, this is usually not an issue, but it's good practice to be aware). - The function should be efficient and modify the vector in place.
Notes
Remember that a mutable reference (&mut T) allows you to modify the data it points to. You can obtain a mutable reference from a mutable binding. Consider how you would iterate over a vector to allow modification of its elements. The iter_mut() method on slices (which Vec dereferences to) is a common and idiomatic way to achieve this.