News for hackers. Stuff that matters.
Re:Things you can’t do in Rust (and what to do instead) by oconnor663 on Saturday May 15, 2021 @08:01PM (#27170061)
Here's a runnable version of the Rust code, with some type annotations removed: https://play.rust-lang.org/?version=stable&mode=debug&editio...

And here are a few broken versions to show the compiler errors you see when you make mistakes:

- Not using Mutex at all: https://play.rust-lang.org/?version=stable&mode=debug&editio...

- Replacing Mutex with RwLock, and then taking a read lock instead of a write lock: https://play.rust-lang.org/?version=stable&mode=debug&editio...

- My favorite, trying to retain a reference past unlocking: https://play.rust-lang.org/?version=stable&mode=debug&editio...

That last example is the most condensed picture of "what Rust is all about" that I know of. Rust itself has no idea what a Mutex (or a thread) is. Mutex is just some library type. But it's able to use the borrow checker to enforce a high-level guarantee, that the contained object is never accessed without holding the lock. This guarantee is checked at compile time, with no runtime overhead. Ownership, borrowing, and lifetimes are about more than just memory safety: library authors can use them to express invariants.

There are no comments on this comment yet.