
📎 This article includes 1 downloadable practice file ↓
“`rust
fn total(items: &[f64]) -> f64 { items.iter().sum() } // borrows
fn add_gst(amount: &mut f64) { *amount *= 1.18; } // mutable borrow
let prices = vec![42000.0, 12800.0];
total(&prices); // prices still usable afterwards
let moved = prices; // ownership moves; `prices` can’t be used now
“`
- Every value has one owner; when the owner goes out of scope, the value is freed.
- Pass
&valueto lend it (read-only),&mut valueto lend it for changes; only one mutable borrow at a time.
These rules, checked at compile time, prevent use-after-free and data races without a garbage collector.
Code for this course follows standard, current syntax; we test JavaScript and PowerShell scripts before publishing, and R/Java/Rust examples are kept to core language features. Tell us if anything fails on your setup.
Practice
Run the file as main.rs, then try using prices after the move and read the error.
📎 Practice files for this article
- 📄rust-ownership.rsLesson code file.⬇ RS · 585 B
Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.
Stuck on a step? Ask a question and the AI answers using this article.