Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

Ownership Rules

Rust has a special system called ownership that makes your programs safe without needing a garbage collector. It's one of the things that makes Rust unique!

The Three Rules

  1. Every value in Rust has a single owner (a variable)
  2. There can only be one owner at a time
  3. When the owner goes out of scope, the value is dropped (cleaned up)

Moving Ownership

When you assign a String to another variable, ownership moves:

rust
fn main() {
let name = String::from("Luna");
let hero = name; // ownership moves to hero
// name is no longer valid here!
println!("{}", hero);
}

After the move, name can't be used anymore — hero is the new owner. This prevents two variables from trying to clean up the same memory!

Copy Types

Simple types like numbers and booleans are copied instead of moved:

rust
fn main() {
let x = 42;
let y = x; // x is copied, both are valid!
println!("x = {}, y = {}", x, y);
}

Numbers live on the stack and are cheap to copy, so Rust copies them automatically.

Moving Into Functions

Passing a String to a function also moves ownership:

rust
fn greet(name: String) {
println!("Hello, {}!", name);
}

fn main() {
let player = String::from("Alex");
greet(player);
// player is no longer valid here!
}

Borrowing with &

What if you want to use a value without taking ownership? You can borrow it with &:

rust
fn greet(name: &String) {
println!("Hello, {}!", name);
}

fn main() {
let player = String::from("Alex");
greet(&player);
// player is still valid!
println!("Player is still: {}", player);
}

A borrow is like lending a book to a friend — they can read it, but you still own it!

Mutable Borrowing with &mut

To let a function change a borrowed value, use &mut:

rust
fn add_title(name: &mut String) {
name.push_str(" the Great");
}

fn main() {
let mut hero = String::from("Luna");
add_title(&mut hero);
println!("{}", hero);
}

Important rules:

  • You can have many & borrows at the same time
  • You can have only one &mut borrow at a time
  • You can't mix & and &mut borrows

Clone

If you really need two separate copies of a String, use .clone():

rust
fn main() {
let name = String::from("Luna");
let backup = name.clone();
println!("Original: {}", name);
println!("Backup: {}", backup);
}

Summary

ConceptWhat it does
OwnershipEvery value has exactly one owner
MoveAssigning a String moves ownership
CopyNumbers and bools are copied automatically
&valueBorrows a value (read-only)
&mut valueBorrows a value (read & write)
.clone()Creates a deep copy of a value

Now let's practice ownership and borrowing!