1

Editor's note: This code is from a version of Rust prior to 1.0 and is not syntactically or semantically valid Rust 1.0 code.

So, scoping out shared box pointers as a learning exercise. Purely academic exercise.

#[feature(managed_boxes)];

struct Monster {
    legs: int
}

fn main() {
    let mut steve = @Monster{ legs: 2 };

    steve.legs = 8;
}

I'm a little surprised to be getting this compiler error:

shared_box.rs:10:5: 10:15 error: cannot assign to immutable field
shared_box.rs:10     steve.legs = 8;

What gives?

The error goes away if I switch to an Owned Box pointer. Is this some kind of restriction on managed pointer access?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Greg Malcolm
  • 3,238
  • 4
  • 23
  • 24

1 Answers1

3

You can't.

  • @ is immutable.
  • Managed boxes are being steadily destroyed, so you shouldn't use them.
  • @mut has been removed from the language.

There is, however, a way of getting around this: RefCell. If you wrap an object in it then you can modify it even though it appears to be immutable. This is sometimes useful, but where possible you should avoid it. Here's an example of using it (with Gc; you should probably tend to use Rc at present instead, because Gc is not properly implemented):

let steve = box(GC) RefCell::new(Monster { legs: 2 });
steve.borrow().borrow_mut().get().legs = 8;
assert_eq!(steve.borrow().borrow().get().legs, 8);

It's not pretty; smart pointer traits may well improve the situation. But where possible, avoid such things. Immutable data is good, task-local data is good.

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • 2
    @GregMalcolm To be clear, the *contents* of `@` is an immutable slot, that is, the `x` in `y = @x` cannot be modified even if the `y` is `mut`. The types like `RefCell` and `Cell` offer "inner mutability" (`RefCell` comes with runtime checks to ensure that no invariants of `&mut` pointers are violated: if a `&mut` pointer exists to a piece of data, then that is the only path by which that data can be touched. Maintaining this invariant is *why* the contents of shared types are immutable by default.) – huon Feb 21 '14 at 11:50