Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top