DEV Community

parsa raad
parsa raad

Posted on Edited on AI-assisted

Rust Ownership Explained for PHP Developers: Move, Borrow, and References

If you come from PHP, memory management is probably something you rarely think about.

You create an object, pass it to another function, assign it to another variable, and PHP takes care of memory management through reference counting and its garbage collector.

Rust takes a different approach.

It doesn't use a garbage collector. Instead, it uses a system called Ownership to manage memory safely at compile time.

This is one of the most important concepts to understand when learning Rust, especially if your background is in PHP or another garbage-collected language.

Let's explore it step by step.

1. What Is Ownership?

Ownership is Rust's system for determining who is responsible for a value in memory.

It is based on three rules:

  1. Every value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value is dropped and its resources are released.

Consider this example:

fn main() {
    let message = String::from("Hello, Rust!");

    println!("{message}");
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • message owns the String.
  • The string remains valid while message is in scope.
  • When main finishes, message goes out of scope.
  • Rust automatically releases the memory used by the string.

You don't need to manually free the memory.

Rust knows when the value is no longer needed and handles cleanup automatically.

2. Stack vs Heap: A Quick Introduction

Before understanding ownership, it's useful to understand where data can be stored.

Rust uses both the stack and the heap.

Stack

The stack stores values with a known, fixed size. It is fast to allocate and deallocate.

Heap

The heap stores data that can grow or whose size isn't necessarily known at compile time.

For example:

let age = 34;
let name = String::from("Parsa");
Enter fullscreen mode Exit fullscreen mode

The integer age is stored directly in the stack frame.

A String has a small structure stored on the stack, containing information such as a pointer, length, and capacity. The actual string data is stored on the heap.

This distinction matters because ownership becomes especially interesting when heap-allocated data is involved.

3. Move Semantics: What Happens When You Assign a Value?

This is where Rust starts behaving differently from what PHP developers might expect.

Consider:

fn main() {
    let first = String::from("Hello");

    let second = first;

    println!("{second}");
}
Enter fullscreen mode Exit fullscreen mode

This code is valid.

But what happens if we try to use first again?

fn main() {
    let first = String::from("Hello");

    let second = first;

    println!("{first}");
}
Enter fullscreen mode Exit fullscreen mode

Rust will refuse to compile this code.

Why?

Because assigning first to second moves ownership of the string.

After the move:

  • second becomes the owner.
  • first is no longer valid.
  • The heap allocation is not automatically duplicated.

This behavior is called Move Semantics.

Why does Rust do this?

Imagine both variables owned the same heap allocation. When both went out of scope, Rust might try to free the same memory twice.

Move semantics prevent this problem by ensuring that only one variable owns the value at a time.

How Is This Different from PHP?

In PHP:

$first = 'Hello';

$second = $first;

echo $first;
echo $second;
Enter fullscreen mode Exit fullscreen mode

Both variables remain usable.

PHP manages the underlying memory automatically. For strings, it can also use copy-on-write internally.

Rust does not implicitly duplicate a String when you assign it to another variable. It transfers ownership instead.

What If I Actually Want a Copy?

You can explicitly clone a value:

fn main() {
    let first = String::from("Hello");

    let second = first.clone();

    println!("{first}");
    println!("{second}");
}
Enter fullscreen mode Exit fullscreen mode

Now both variables are valid because clone() creates a separate copy of the string data.

This distinction is important:

  • move: transfers ownership.
  • clone(): explicitly duplicates the value.

Don't use clone() everywhere just to make compiler errors disappear. Cloning heap-allocated data can have a performance cost.

4. The Copy Trait: Not Everything Is Moved

Rust has an important exception to the move behavior.

Some types implement the Copy trait.

For example:

fn main() {
    let first = 10;

    let second = first;

    println!("{first}");
    println!("{second}");
}
Enter fullscreen mode Exit fullscreen mode

This works.

Why?

Because integers implement Copy.

When you assign first to second, Rust copies the value instead of moving ownership.

Common types that implement Copy include:

  • Integer types such as i32 and u64
  • Floating-point types such as f64
  • bool
  • char
  • Tuples containing only Copy types

However, String does not implement Copy.

A useful distinction:

Operation Behavior
let b = a where a is a String Move
let b = a.clone() Clone
let b = a where a is an i32 Copy

5. Borrowing and References: Use Data Without Owning It

Moving ownership is useful, but what if a function only needs to read a value?

You probably don't want to transfer ownership every time you call a function.

This is where Borrowing comes in.

Consider this example:

fn main() {
    let name = String::from("Parsa");

    print_name(&name);

    println!("{name}");
}

fn print_name(value: &String) {
    println!("{value}");
}
Enter fullscreen mode Exit fullscreen mode

Notice the & symbol.

Instead of passing ownership of name, we pass a reference to it.

The function can access the string without becoming its owner.

This is called borrowing.

The original variable remains the owner, and the borrowed reference provides temporary access to the value.

PHP Comparison

In PHP, you might write:

function printName(string $name): void
{
    echo $name;
}

$name = 'Parsa';

printName($name);

echo $name;
Enter fullscreen mode Exit fullscreen mode

PHP allows this without you thinking about ownership.

In Rust, the function signature explicitly tells us whether it takes ownership or borrows the value.

Compare:

fn process(value: String) {
    println!("{value}");
}
Enter fullscreen mode Exit fullscreen mode

This function takes ownership.

But:

fn process(value: &String) {
    println!("{value}");
}
Enter fullscreen mode Exit fullscreen mode

This function only borrows the value.

That small difference changes how the caller can use the variable afterward.

6. Mutable References: Borrowing and Modifying Data

So far, we've only borrowed data for reading.

What if a function needs to modify the original value?

Rust provides mutable references using &mut.

fn main() {
    let mut message = String::from("Hello");

    add_world(&mut message);

    println!("{message}");
}

fn add_world(value: &mut String) {
    value.push_str(", world!");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, world!
Enter fullscreen mode Exit fullscreen mode

There are two important details here:

  1. The original variable must be declared with mut.
  2. The function must accept a mutable reference using &mut String.

Rust makes mutation explicit.

You cannot modify a value through an ordinary immutable reference.

The Most Important Borrowing Rule

Rust enforces a rule that can initially feel restrictive:

At any given time, you can have either:

  • Any number of immutable references (&T), or
  • Exactly one mutable reference (&mut T).

But you cannot have both simultaneously.

For example:

fn main() {
    let mut message = String::from("Hello");

    let first = &message;
    let second = &message;

    println!("{first} {second}");
}
Enter fullscreen mode Exit fullscreen mode

This is valid. Multiple immutable references are allowed.

But this is not:

fn main() {
    let mut message = String::from("Hello");

    let first = &message;
    let second = &mut message;

    println!("{first} {second}");
}
Enter fullscreen mode Exit fullscreen mode

Rust rejects this because an immutable reference and a mutable reference are being used at the same time.

Why is this important?

Imagine one part of your program is reading data while another part modifies it.

Without proper rules, you could encounter unpredictable behavior.

Rust prevents this category of data race at compile time by enforcing controlled access to shared data.

Think of it as:

Multiple readers OR one writer.

Not both at the same time.

7. Dangling References: Rust Prevents Invalid Memory Access

A dangling reference happens when a reference points to memory that is no longer valid.

Consider this example:

fn main() {
    let reference = create_reference();
}

fn create_reference() -> &String {
    let message = String::from("Hello");

    &message
}
Enter fullscreen mode Exit fullscreen mode

This code doesn't compile.

Why?

Because message is created inside create_reference().

When the function finishes, message goes out of scope and its memory is released.

Returning a reference to that value would create a reference to invalid memory.

Rust's compiler catches this problem before the program runs.

This is another important part of ownership and borrowing: references cannot outlive the data they refer to.

8. How Does This Compare to PHP Memory Management?

Let's compare the two approaches.

Concept PHP Rust
Memory management Automatic Ownership system
Garbage collector Yes, for cyclic references No garbage collector
Variable assignment Usually remains usable May move ownership
Memory cleanup Runtime-managed Deterministic drop
Shared access Runtime-managed Borrowing rules
Mutable access Generally unrestricted by the type system Explicit mutable borrowing
Dangling references Managed through runtime semantics Prevented by compiler rules

One important clarification: PHP and Rust have different memory models, so PHP assignment is not directly equivalent to Rust ownership transfer.

PHP uses reference counting and copy-on-write for certain values, alongside garbage collection for cycles.

Rust uses ownership, borrowing, and lifetimes to ensure that memory is accessed safely without requiring a garbage collector.

9. A Practical Example: Passing Data Between Functions

Let's put these concepts together.

Imagine we have a function that calculates the length of a user's name.

We don't need to transfer ownership because the function only needs to read the string.

fn main() {
    let username = String::from("parsa");

    let length = calculate_length(&username);

    println!("Username: {username}");
    println!("Length: {length}");
}

fn calculate_length(name: &String) -> usize {
    name.len()
}
Enter fullscreen mode Exit fullscreen mode

Now imagine we want to modify the username:

fn main() {
    let mut username = String::from("parsa");

    update_username(&mut username);

    println!("{username}");
}

fn update_username(name: &mut String) {
    name.push_str("_dev");
}
Enter fullscreen mode Exit fullscreen mode

And finally, imagine we want to transfer ownership:

fn main() {
    let username = String::from("parsa");

    save_username(username);
}

fn save_username(name: String) {
    println!("Saving username: {name}");
}
Enter fullscreen mode Exit fullscreen mode

Each function communicates its relationship with the data through its parameter type.

  • String: Takes ownership.
  • &String: Borrows for reading.
  • &mut String: Borrows for modification.

This makes function behavior much easier to reason about.

10. Final Thoughts

Ownership is probably one of the biggest mental shifts when moving from PHP to Rust.

In PHP, you usually let the runtime handle memory management.

In Rust, the compiler requires you to be explicit about who owns data and how other parts of the program can access it.

The three concepts to remember are:

  1. Move: Ownership is transferred from one variable to another.
  2. Borrow: A reference allows temporary access without transferring ownership.
  3. Mutable Borrow: A mutable reference allows modification, while enforcing exclusive access.

Once these concepts become familiar, many Rust compiler errors start making sense.

Instead of seeing the borrow checker as an obstacle, think of it as a tool that catches memory-safety problems before your application runs.

And that's the real power of Rust's ownership system.


References

Top comments (0)