Loading
0x20Lesson 3 of 6

Understand ownership and borrowing

Learn Rust’s core memory-safety model.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Explain move semantics and pass references to avoid ownership transfer.

Every value in Rust has one owner. When ownership moves, the previous binding is no longer valid. Borrowing with references (&T) lets you read data without taking ownership. Mutable borrows (&mut T) allow controlled updates with strict aliasing rules.

main.rs
1fn length(text: &String) -> usize {
2    text.len()
3}
4
5fn main() {
6    let message = String::from("rustacean");
7    let size = length(&message);
8    println!("{}", size);
9}
Output
9

Ownership and borrowing eliminate many memory bugs without garbage collection. Start by asking: “Who owns this value now?” and “Do I need ownership, or just a borrow?”.

Key takeaways

  • Explain move semantics and pass references to avoid ownership transfer.

  • Rust uses types and ownership rules to prevent common bugs.

  • Small experiments build intuition quickly.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Rust

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.

Exercise 1

Borrow and print length

+25 XP

Complete word_length to take a borrowed String and return its length, then print it.

  • Fixed word
main.rs
Loading editor…

Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: