Decoupling of vector container mutability vs vector element mutability

Hello.

I am wondering if there is a way to make a container (eg Vec) immutable in that its size or the objects that it points to cannot be changed while allowing the elements to be modified.:

struct Point {
    x: i32,
    y: i32,
}
impl Point {
    fun mutate(&mut self) { .. .}
}
let v : Vec<Point> = ...;
v.push( Point{x:0,y:0} );  // disallowed
v[0] = Point{x:0, y:0}; // disallowed
v[0].x = 4;  // allowed
v[0].mutate() // allowed

Thanks.

There is a confusion here: for Vec<Point> there is no such thing as "changing where some entry points to". This Vec's elements are the Point objects, not pointers to Points. This has implications as you will see below.

You can get roughly what you want via a slice reference:

    let v: &mut [Point] = &mut vec![Point {x:3, y:4}];    
    //v.push( Point{x:0,y:0} );  // disallowed
    v[0] = Point{x:0, y:0}; // allowed
    v[0].x = 4;  // allowed
    v[0].mutate() // allowed

The second case needs to be allowed if the third and fourth are allowed because assignment is a particular case of a mutating operation. It doesn't assign a pointer to a new Point object located elsewhere -- it mutates the Point by replacing it.

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.