4 ms·
My short comment was a bit tongue in cheek. > A good tool shouldn’t require you to have a perfect memory of all the rules for you to be highly productive with
by bombela 2y ago
My short comment was a bit tongue in cheek.
> A good tool shouldn’t require you to have a perfect memory of all the rules for you to be highly productive with it. If you make mistakes it should quickly tell you so with a message that quickly lets you figure out what to change.
That's exactly what the Rust borrow checker does for me.
The borrow checker rules are quite simple conceptually.
If I own a book, I can read it, write in the margins or even destroy it. `let book: Book = Book{...}`.
I can lend this book to you exclusively `&mut Book`, you can read and write it, but not destroy it. And nobody else; including me; can even read it until you are done.
I can lend this book to you and others for reading `&Book`. We can all read it concurrently. And I must wait for everybody to be done before I can regain full ownership.
I can give you the book (passing by value). And it's now yours to do what you please. Including destroying it `drop(Book)`.
Sometimes you do want to share to many; and maybe even gate exclusive write access; at runtime. This is where Rc, Arc, Cell, RefCell and Mutex come in.
Rc and Arc destroy the book when a reference counter drops to zero. Another way to look at it, is that when the counter is 1, you have sole ownership of the book. And you can do with it what you please.
As for the runtime check for mutability, Mutex should be obvious. Cell and RefCell are similar but within a single threaded context.
And finally when you know better than the compiler, you use pointers (instead of references) and triple check your work within `unsafe` blocks.