On 11/12/13 9:51 PM, Oren Ben-Kiki wrote:
If sending the whole thing is an issue, you are pretty much forced to
use Arc<T> (and forget about reference cycles). And, of course, each of
these (Rc, @, Arc) has a different name if you want mutation (RcMut,
@mut, ArcRW).

I think having to choose between thread-safe and non-thread-safe reference counting is just part of systems programming. But the mutation part is painful. I'd like to move most code that uses `@mut` and friends to the `Slot` pattern that I'm starting to use in Servo, whereby you wrap individual fields in `Slot`s and just use `.get()` and `.set()`, instead of making the entire object mutable. So for example:

    struct MyObject {
        x: Slot<int>,
        y: Slot<int>,
    }

    let obj = Rc::new(MyObject {
        x: Slot::init(1),
        y: Slot::init(2),
    });
    println!("{} {}", obj.x.get(), obj.y.get());
    obj.x.set(obj.x.get() * 2);
    obj.y.set(obj.y.get() * 3);

The biggest nice thing about this is that you don't have to worry about all of those dynamic borrow failures. (Slots support borrowing in case you have to have a reference to the value for some reason, but `.get()` and `.set()` are preferred, as sticking to those will prevent you from ever having dynamic borrow check failures.)

The other nice thing is you don't have to use separate mutable smart pointers. You can write `Rc<whatever>` instead of `RcMut<whatever>`.

In performance-critical code I sometimes give up and just have an array
of ~T and use an unsafe ptr to T in all my other references... which is
OK as long as these only live as long as the container, but I get zero
compiler support for that. I wish there was a way to say "this borrowed
pointer lives only as long as its container". That doesn't seem to be in
the cards though :-(

I don't know how to make that sound, unfortunately, other than using an arena and allocating all the nodes into it (losing the ability to deallocate individual nodes).

Patrick

_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to