3 ms·
Here's a runnable version of the Rust code, with some type annotations removed: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4d68d397
by oconnor663 5y ago
Here's a runnable version of the Rust code, with some type annotations removed: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4d68d3972b6b89a82baf621922480917 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&edition=2018&gist=b17ef279b82a775ed6da5dcc69ceeeaf 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&edition=2018&gist=a283aa367774440058e51dfc9b7c85a3 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&edition=2018&gist=359462a6bc6893c6378964bd32344ae4 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.