The 3 important facts in Rust: Tree-shaped ownership. In Rust's ownership system, one object can own many children or no chlld, but must be owned by exactly one parent. Ownership relations form a tree. 1 Mutable borrow exclusiveness. If there exists one mutable borrow for an object, then no other borrow to that object can exist. Mutable borrow is exclusive. Borrow is contagious. If you borrow a child, you indirectly borrow the parent (and parent's parent, and so on). Mutably borrowing one wheel of a car makes you borrow the whole car, preventing another wheel from being borrowed. It can be avoided by split borrow which only works within one scope. Considering reference shape Firstly consider the reference 2 shape of your in-memory data. If the reference is tree-shaped, then it's simple and natural in Rust. If the reference shape has sharing, things become a little complicated. Sharing means there are two or more references to the same object. If shared object is immutable: If the sharing is scoped (only temporarily shared), then you can use immutable borrow. You may need lifetime annotation. If the sharing is not scoped (may share for a long time, not bounded within a scope), you need to use reference counting (Rc in singlethreaded case, Arc in possibly-multithreaded case) If shared object is mutable, then it's in borrow-check-unfriendly case. Solutions elaborated below. Contagious borrow can cause unwanted sharing (elaborated below). If the reference shape has cycle, then it's also in borrow-check-unfriendly case. Solutions elaborated below. The most fighting with borrow checker happens in the borrow-check-unfriendly cases. Summarize solutions The solutions in borrow-checker-unfriendly cases (will elaborate below): Data-oriented design. Avoid unnecessary getter and setter. Do split borrow in outer scope and pass borrowing of each component separately. Use ID/handle to replace borrow. Use arena to hold data. Defer mutation. Turn mutation as commands and execute la...
First seen: 2025-10-24 16:37
Last seen: 2025-10-24 16:37