I've found lots of questions asking about immutable to mutable, but am not quite sure what I am doing wrong in this code.
The error I am getting is:
"cannot borrow values as immutable because it is also borrowed as mutable"
fn modify_vec_get_slice(values: &mut Vec<i32>) -> &[i32] {
// Modify "values" in some way
values.push(5);
// Return a slice into "values" (dummy code)
values.split_at(values.len() / 2).1
}
fn use_slice(slice: &[i32]) {
// Do something immutably with the slice
}
fn use_vec(values: &Vec<i32>) {
// Do something immutably with the vec
}
fn main() {
let mut values = vec![1, 2, 3, 4];
let slice = modify_vec_get_slice(&mut values); // use values mutably
use_vec(&values); // Error here is "&values" underlined in red, even though "values" is used immutably
use_slice(slice); // use slice immutably (which refers to the vec?). Uncommenting this line fixes the error
}
Why can't I use the slice (an immutable reference) when I can use &values (also an immutable reference)? Surely the mutable reference used in "modify_vec_get_slice" has ended by the time I get to the other functions?