3 ms·
Say I'm "single threaded" (more simple). When to use Rc/RefCell then?
by MuffinFlavored 3y ago
Say I'm "single threaded" (more simple). When to use Rc/RefCell then?
- cmrdporcupine 3y agoAs 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 or there are other mutable references. People use this for the "interior mutability pattern"; Additional 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.
- duped 3y agoYou 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).