DEV Community

[Comment from a deleted post]
Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

It's meant to solve a data safety issue that occurs when multiple write accesses happen at the same time (whether on a single thread or multiple threads).

For example, consider a common example below, in a mutable context (we're able to mutate values), from other languages. Assume that we're taking a reference/pointer to the items (not a copy).

var a = this.items[1];
var b = this.items[2];

b.value += a.value

This type of code will violate the borrow checker rules in Rust. TO understand why let's introduce a new statement:

var a = this.items[1];
this.something();
var b = this.items[2];

b.value += a.value

From this code we don't know what something() does. If it removes an item from items then the code is invalid, since a may no longer below to that list, or it may be a different location. Without knowing precisely what something() does the code is not valid.

This is the type of error the borrow checker is protecting against.

The lack of this.something() is just a minor variation that doesn't change the overall correctness. But it really depends on the signatures of the various functions as to where the borrow rules get violated.

I've chosen an example that applies even in a language that uses a scanning GC: the logical error persists. In Rust the default lifetime is bound to a scope, with move semantics on assignment. References as thus bound and limited to particular scopes. This requires strict correctness on the part of the borrow checker: logically invalid ops could otherwise lead to memory corruption.

I'm still keeping an open mind about Rust's features, and definitely see value in this one. However, at the moment it complicates common algorithms, and the dependency tracker seems to encourage unclean code, such as the train-wreck anti-pattern.

Collapse
 
nestedsoftware profile image
Nested Software

What would be the idiomatic Rust way to do this kind of thing then? Also I’d love to know what the train-wreck antipattern is!