Prevent a mutable slice reference from being modified

Given the following situation:

let s = &mut [0, 1, 2];       // s: &mut [i32;3]
let s = &s;                   // s: &&mut [i32; 3] (shadowing)

I think there is now no way to modify the values in the original slice. Since s is a reference to a &mut ... which is not Copy, then it is not possible to get access to a mutable reference of the original slice.
Is this true?

Well, you can't get a &mut T from a &&mut T, so yes, in your example there is no way to mutably access the value without UB (if we leave out interior mutability) as long as the mutable reference is shadowed. If T would be Copy you would still be unable to change the value at the original location, you could only modify the copy you created.

2 Likes

You might want to do this with a reborrow instead:

let s = &mut [0, 1, 2];       // s: &mut [i32;3]
let s = &*s;                  // s: & [i32; 3] (shadowing)

It accomplishes basically the same thing, but without the awkward double-reference in the type. Even if you don’t shadow s, but instead give a new variable name s2 to the second assignment, the borrow checker will prevent changes to the slice through either s or s2 until the last use of s2.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.