News for hackers. Stuff that matters.
Re:Effective Rust by MuffinFlavored on Thursday June 15, 2023 @12:13PM (#36342698)
Say I'm "single threaded" (more simple). When to use Rc/RefCell then?
Re:Effective Rust by cmrdporcupine on Thursday June 15, 2023 @12:51PM (#36343291)
As I said above, roughly:

Rc for if you have some piece of data shared between (non-concurrent) components, that is maybe hard to manage with borrowing? I personally would try to fix this rather than rely on Rc, but there are legit cases.

RefCell for if you want to manage the borrowing at runtime instead of at compile. Basically it will raise a panic at runtime if more than one person borrows off it.

And it allows you to borrow something mutably (borrow_mut()) even if the surrounding thing is immutable. So people use this for the "interior mutability pattern"; So examples would be e.g.: I have an internal counter I want to increment every time you call this function, and that's mutable, but the surrounding ref to the struct is immutable and I want to keep it that way. I could keep the counter in a RefCell and then borrow it immutably into a RefMut even tho the context I'm doing it in is immutable.

It's basically "unsafe" code, really, buyer beware. Apply carefully.

Re:Effective Rust by duped on Thursday June 15, 2023 @01:29PM (#36343881)
You use `Rc` when a value can have more than one owner. You use `RefCell` when you need multiple mutable references to a value in scope (aka interior mutability - there are more than one mutable references held, but the borrow checker can't prove that they don't overlap at compile time).