Ramblings of an aging IT geek
← Ramblings of an aging IT geek
rust

the day the borrow checker was right and i was wrong

A small Rust refactor I was sure the compiler had got wrong turned out to be a real aliasing bug, and the fix was to stop fighting and restructure the data.

A code editor with Rust source on screen

I had a function that walked a vector, found an entry, and mutated it while also pushing a new entry onto the same vector. The borrow checker said no, repeatedly, and I spent a good half hour convinced it was being pedantic. It was not. If the push reallocated, my mutable reference into the old buffer would have been pointing at freed memory. The compiler was describing a real bug that C would have happily let me ship.

The reflex is to reach for clone() and make the error go away. That works and it's sometimes the right call, but here it would have hidden the actual shape of the problem, which was that I was trying to read and grow the same structure in one pass. Two passes fixed it: collect the indices I wanted to touch, then apply the changes. Slightly more code, no unsafe, and the intent reads more clearly than the clever version ever did.

The honest lesson is that "losing" to the borrow checker is usually it telling you your ownership story doesn't hold together. Once I stopped treating it as an obstacle and started treating it as a reviewer who never gets tired, the arguments got a lot shorter. I still lose. I just lose faster now, and I learn something each time.