Home
Blog
Rust Borrow Checker Tips
Updated
Dot Net Perls

Rust Borrow Checker Tips

Suppose you are writing a Rust program, and you are having problems with the borrow checker. The compiler is giving you messages about "use of moved value" and "cannot borrow data as mutable." Should you give up?

No, you should not give up. Instead, here are some tips for dealing with the borrow checker.

Store all elements in a struct, and then reference those elements by index from elsewhere in the program.
Use indexes (like usize values) instead of references.
Clone structs when needed to fix some "moved value" issues, and wrap structs in Arcs to make cloning much faster.

Basically in Rust it helps to know what struct owns all the memory in a program. Then you don't have to worry about the memory anymore—you can just access the data by index, referencing the owner struct. In this approach, most structs do not need to store references to other structs.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen