Hacker News new | ask | show | jobs
by saghm 1482 days ago
& versus &mut (and the associated borrow checker rules) also stop certain types of bugs in non-concurrent code. For example, if you try to get a reference to an element in a vector, then try to clear the vector, the compiler will not allow it since you need a mutable reference to call the `clear` method, which can't be taken while a reference to an element exists (unless the reference isn't used again after the clear, in which case the compiler will recognize the lifetimes of the references don't overlap). In a GC language, the referenced object could still be kept around without needing to remain in the vector, but in a language like C/C++, you'd end up with a dangling pointer: https://play.rust-lang.org/?version=stable&mode=debug&editio...

(edited to replace poorly formatted inline code with link to playground)