Rust ownership exercises
Rust eliminates data races and memory corruption through its ownership system, but understanding borrow scopes, mutability rules, and move semantics is the steepest learning curve for any Rust developer.
Work through real code snippets that trigger borrow checker errors and learn the idiomatic fixes: cloning, scoped borrowing, and refactoring.
The ownership bugs you will meet
- Cannot borrow as mutable more than once at a time: only one &mut T is allowed in a given scope.
- Value used here after move: non-Copy types like String and Vec transfer ownership when assigned or passed by value.
- Cannot move out of a borrowed reference: you cannot take ownership from &T without cloning or using Option::take.
- Returning a reference to a local variable created inside a function is forbidden.
The exercises
Easy
Medium
- Unexpected runtime panic during file processingNull and undefined
- String slice panics on non-UTF-8 char boundaryMutation and copying
- Immutable reference error during vector mutationScope and closure
- Persistent memory usage despite object deletion in RustLogic
- Struct usage error after partial move in RustScope and closure
- Unexpected file descriptor leak in Rust applicationLogic
- Unexpected Panic When Slicing a String in RustLogic
- String modification fails with Cow always borrowing issueScope and closure
- UTF-8 byte index is not a char boundary panicLogic
- Truncate string on non-char boundary panicsLogic
- Cursor position at EOF returns zero bytesLogic
- Downcast on Box dyn Any fails with wrong typeType
- Borrow checker vector mutation during element iterationScope and closure
- Regex compilation overhead in repetitive loopLogic
- Partial move from struct prevents usageScope and closure
- Cow always clones to owned unnecessarilyLogic
Errors you might be searching for
More JavaScript practice by topic
Questions
Why does Rust disallow two mutable references?
Allowing multiple mutable references can cause data races in concurrent code and pointer invalidation when resizing collections.