Hi everyone!
Do concepts like ownership and borrowing specifically exist in Rust to prevent UB in multithreaded context? (In multithreaded env, it's quite clear: forcing the spawned thread to take ownership of a String. This prevents other threads from modifying it at the same time.)
Or it's applications shine in single threaded contexts as well? Thanks!
Rust rules are indeed most important for multi-threading. But even in single-threaded code, without those rules, problems like dangling pointers could arise. What might be a bit difficult to understand for a beginner is, why even in single-threaded code only one exclusive reference is allowed. Details are explained in most Rust books, e.g. see Ownership and memory management - Rust for C-Programmers
The classic example where it shines in a single-threaded context is iterator invalidation.
If I write:
const CLEAR_THE_DECKS: u32 = 42;
let mut input = vec![];
// Code filling in the Vec
for item in input {
if item == CLEAR_THE_DECKS {
input.clear()
}
The borrow checker rejects my code because I'm mutating the same Vec<u32> (input) while I've also got it borrowed so that I can iterate over it.
In general, safe Rust enforces, at compile time, that you either have exactly one way to refer to something, in which case you can change it, or you have multiple references to the thing, in which case it's immutable. As code gets more complicated, the checks provided this way ensure that you spot your mistakes before they break at runtime.