Sharing mutable state: Go mutex vs Rust Arc Mutex
shared-state concurrency and compile-time safety.
Go uses sync.Mutex by convention; Rust wraps data in Arc<Mutex<T>> so locking is mandatory, enforced by Send/Sync and the borrow checker.
WHAT THIS TESTS Whether you grasp shared-memory concurrency in both languages and can distinguish conventions enforced by discipline from invariants enforced by the type system.
A GOOD ANSWER COVERS In Go, the idiom is a struct holding a sync.Mutex next to the field it protects; every accessor calls mu.Lock and defer mu.Unlock. The association between lock and data is a convention, not enforced, so forgetting to lock compiles and silently races. In Rust, you wrap the value in Mutex<T>, and because the only way to obtain &mut T is by calling lock and holding the returned guard, locking is structurally mandatory. Arc<Mutex<T>> adds atomically reference-counted shared ownership so multiple threads can each hold a handle. The compiler enforces this through the Send and Sync auto-traits and the borrow checker, which together reject data races before the program runs.
COMMON WRONG ANSWERS Saying Go prevents data races at compile time; it does not, it offers a runtime race detector you must opt into. Claiming Rust's Mutex has no runtime cost; it still locks. Confusing Rc with Arc, where Rc is not thread-safe.
LIKELY FOLLOW-UPS What does the MutexGuard do on drop, and how does poisoning work after a panic? Why Arc over Rc here? When would you prefer channels or sync/atomic instead?
ONE CONCRETE EXAMPLE A shared counter across ten threads: in Rust, let c = Arc::new(Mutex::new(0)); each thread clones the Arc, locks, and increments; forgetting to lock will not compile because the integer is unreachable without the guard. The equivalent Go counter requires the author to remember mu.Lock; omitting it compiles and produces a race detectable only at runtime.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.