Hacker News new | past | comments | ask | show | jobs | submit login

not that steve isn't correct but Rc and Arc effectively (in exchange for runtime overhead) "turn off" the borrow checker. i'm sure i'll get yelled but it's just this week i had the borrow checker yelling at me for something and i realized that the appropriate thing to do was use Arc (yes of course i'm not advocating for ref counting instead of being more precise).



Rc and Arc are about (shared) ownership not borrowing. If they're turning off anything, it's ownership. Borrowing works the same way as ever.

In fact that's an advantage of Rust here: because of the borrow checker you can safely get a reference to an Rc's contents and hand it off to something without having to alter the refcount, so you get significantly less refcount traffic than in other languages where such a thing is unsafe (or not under your control). That's especially important for Arc.

It also provides for nice safe optimisations like "move out of this Rc if I'm the only owner" (Rc/Arc::try_unwrap).


I think you are confusing Rc/Arc with RefCell, since they are often used together. In order to provide interior mutability, the borrow_mut method of RefCell takes &self rather than &mut self. So, it is possible to obtain two mutable references. The following compiles:

    let c = RefCell::new(42usize);
    
    let mut mut_ref1 = c.borrow_mut();
    let mut mut_ref2 = c.borrow_mut();
    
    *mut_ref1 += 1;
    *mut_ref2 += 2;
RefCell uses UnsafeCell to subvert the borrows checker. However, instead RefCell implements run-time borrow checks. So, the code above will panic while attempting to do the second mutable borrow. It is a trade-off. You lose catching errors during compilation, but you can have interior mutability.

This is one of the goals of unsafe, which UnsafeCell requires. Sometimes, you need to do something that safe Rust does not permit, but that you can prove to be safe (such as RefCell).

That said (and it depends a bit on your domain), I have used Rust for probably 1.5 years without using Arc, Rc, and RefCell. The first time I needed these types when was writing a Gtk+ application and later in some multi-threading programs.

These three types are very easy to overuse when you are coming from other languages. IMO it is better to avoid them and try to work with the borrows checker until you have sufficient experience with Rust to identify when interior mutability and reference counting are really necessary.


One of my major points is that "avoiding the borrow checker" and "turning off the borrow checker" are two distinct ideas.

When dealing with unsafe code, it's very important to know exactly what's going on. Thinking that it turns off checks leads to you misunderstanding what's going on, and that's dangerous.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: