Rust Lesson 3: Ownership and Borrowing

📎 This article includes 1 downloadable practice file ↓

⏱ 1 min read

📘 Rust Beginner Course · Lesson 3 of 6

“`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 &value to lend it (read-only), &mut value to 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

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.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *