Ownership

Rust
Author

Quasar

Published

November 17, 2025

Ownership

Introduction

Ownership is the most important feature of Rust. It allows Rust to be memory-safe and efficient, while avoiding garbage collection. Consider the below mistake that all of us who have used a non-GC’d language have made at one point:

fn as_str(data: &u32) -> &str{
    // Compute the string
    let s = format!("{}", data);

    // Oh No! We returned a reference to something that
    // only exists in this function.
    // Dangling reference! Alas!
    return &s;
}

pub fn main(){
    let x : u32 = 42;
    as_str(&x);
}

Compiler Explorer

[quantdev@quasar-arch ownership]$ rustc ./dangling_reference.rs -o ./dangling_reference
error[E0515]: cannot return reference to local variable `s`
 --> ./dangling_reference.rs:8:12
  |
8 |     return &s;
  |            ^^ returns a reference to data owned by the current function

error: aborting due to 1 previous error

References

There are two kinds of references:

  • Immutable reference &
  • Mutable reference &mut

which obey the following rules:

  • A reference cannot outlive its referent.
  • A mutable reference cannot be aliased.

Aliasing

Consider this simple function:

fn compute(input: &u32, output: &mut u32){
    if *input > 10{
        *output = 1;
    }
    if *input > 5{
        *output *= 2;
    }
}