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

> use only when needed

I don't know when to use them/I probably just go for Arc<Mutex<T>> instead when I probably shouldn't?




You only need the Arc<Mutex if you have multiple threads touching something. And don't worry, the compiler will let you know you gone-messed-up before you get there by angrily telling you about your lack of Send and Sync all over.

Honestly, if you are in a multithreaded world, you are going to make your life a lot easier by reducing your shared mutable state and instead using channels (crossbeam or mpsc) to communicate and coordinate. This will reduce your need to toss things in Arc<Mutex, and in fact reduce a lot of borrow checker issues generally.


Say I'm "single threaded" (more simple). When to use Rc/RefCell then?


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 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.


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).




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: