Why can't I pass data to a function when that function is not going to modify it and the ownership context doesn't end there?
This code gives an error:
let mut ar = [1, 2, 3, 4, 5];
let slice = &mut ar[1..=3];
slice[1] = 9;
println!("{:?} ", slice);
for e in ar.iter(){
println!("{}", e)
}
This is the error:
error[E0502]: cannot borrow `ar` as immutable because it is also borrowed as mutable
--> src/main.rs:6:14
|
3 | let slice = &mut ar[1..=3];
| -- mutable borrow occurs here
...
6 | for e in ar.iter() {
| ^^ immutable borrow occurs here
...
9 | }
| - mutable borrow ends here
My guess is that we can't pass the array to the println!
function because we have borrowed it, but I can't understand why. It's not like the println!
function will change it!
I find the following behaviour difficult to understand. How can I print an array if I have slices of it?
This code works and prints [2, 9, 4]
let mut ar = [1, 2, 3, 4, 5];
let slice = &mut ar[1..=3];
slice[1] = 9;
println!("{:?} ", slice);
Also, this code works and prints everything properly, by modifying the slice we modify the original array!
let mut ar = [1, 2, 3, 4, 5];
{
let slice = &mut ar[1..=3];
slice[1] = 9;
println!("{:?} ", slice); // -> [2, 9, 4]
}
for e in ar.iter(){
println!("{}", e) //-> 1 2 9 4 5 as expected since the slice has changed
}