How to define a immutable variable hold a mutable array?

let mut a = [1, 2, 3, 4, 5];
let r: &mut [i32] = &mut a; // ok, I can modify `a` now.
a = [2, 3, 4]; // I want to prohibit this!

let a = [1, 2, 3, 4];
let r: &mut [i32] = &mut a; // compile error

You could use the slice directly:

fn main() {
    let a: &mut [i32] = &mut [1,2,3,4,5];
    a[0] = 0;
    println!("{:?}",a);
}

Or even closer to your intention, use a mutable reference to that type directly:

fn main() {
    let a: &mut [i32;5] = &mut [1,2,3,4,5];
    a[0] = 0;
    println!("{:?}",a);
}

I believe the compiler will optimize this pointer indirection away.

2 Likes

Thank you very much!