HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RustVariablesData TypesOperatorsStringsVectors (Vec)Conditions (if / match)Loops (for / while)FunctionsOwnership & Borrowing
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Vector & HashMap
🔁 Condition & Loop
🧩 Function
🔑 Ownership & Borrowing
Rust›Ownership & Borrowing

Ownership & Borrowing

Rust's signature feature: a single owner for every value and borrowing with & — memory safety.

Simple enough for a 5-year-old to understand

Ownership: every value has an owner

In Rust, assigning a String to another variable MOVES ownership; the old one can no longer be used. This rule ensures memory safety without a garbage collector.

Example code
1
fn main() {
2
let s1 = String::from("Alex");
s1 is the owner.
Variables1 is the owner.
3
let s2 = s1;
Ownership MOVED to s2 (s1 is now invalid).
VariableOwnership MOVED to s2 (s1 is now invalid).
4
println!("{}", s2);
Alex
Output / InputAlex
5
}
VariableOutput / Input
💡 Hint: Using s1 after the move is a compilation error — Rust prevents this.

About this topic

Ownership is the single idea that sets Rust apart from other languages, and the rest of the language is built upon it. The rule is summarized in three sentences: every value has a single owner, it can only have one owner at a time, and when the owner goes out of scope, the value is dropped.

The consequence of this rule is that you don't need to think about when to free memory because the compiler determines it while the code is being written. There is no garbage collector, no manual deallocation, and still no leaks or double frees.

When you don't want to transfer ownership, you lend it: you take a reference. The rule for borrowing is also clear — you can have either a single mutable reference or multiple immutable references at the same time, but not both together. This rule makes data races impossible at compile time.

What you will learn

  • The ownership rule and dropping at the end of scope
  • The difference between move and copy
  • The rules of borrowing
  • That mutable and immutable references cannot be used together
  • When clone is necessary

Who is this for?

  • Anyone wanting to understand Rust's compiler errors
  • Those who have dealt with memory errors in C or C++
  • Those coming from garbage-collected languages who are curious about Rust's model

When to use?

When passing a value to a function, a reference is almost always given; transferring ownership is only necessary if the function will store the value.

clone is used when a copy is truly needed. Typing clone to silence a compiler error works, but it incurs unnecessary copying costs; check if a reference is sufficient first.

Common mistakes

Wrong

fn main() {
    let a = String::from("hello");
    let b = a;
    println!("{}", a);
}

Assignment MOVES ownership to b; a is now invalid and the compiler gives the error "borrow of moved value: a". This is a move, not a copy. If there were two separate owners, both would try to free the same memory, causing a double free error; Rust prevents this from the start.

Correct

fn main() {
    let a = String::from("hello");
    let b = &a;
    println!("{} {}", a, b);
}

Wrong

fn main() {
    let mut text = String::from("hello");
    let r1 = &text;
    let r2 = &mut text;
    println!("{} {}", r1, r2);
}

A mutable reference cannot be taken while an immutable reference is alive; the compiler gives the error "cannot borrow text as mutable because it is also borrowed as immutable". The reason is: if one reads while another modifies, the read data becomes inconsistent. This rule makes data races impossible.

Correct

fn main() {
    let mut text = String::from("hello");
    let r1 = &text;
    println!("{}", r1);
    let r2 = &mut text;
    r2.push_str(" world");
    println!("{}", r2);
}

Wrong

fn build() -> &String {
    let text = String::from("hello");
    &text
}

fn main() {
    println!("{}", build());
}

text is destroyed when the function ends; returning a reference to it creates a dangling reference and the compiler gives the error "missing lifetime specifier". In C, this code compiles and reads corrupted data at runtime. In Rust, the solution is to return the VALUE, not a reference.

Correct

fn build() -> String {
    let text = String::from("hello");
    text
}

fn main() {
    println!("{}", build());
}

Frequently asked questions

Why don't integers move?

Because simple types are marked as copy: they have a fixed size and live on the stack, so copying them is cheap. String, on the other hand, owns memory outside the stack, making copying costly; Rust doesn't make that decision for you, it moves it.

Is it a problem to use clone everywhere?

It compiles, but it incurs unnecessary copying costs. Typing clone to silence a compiler error is an understandable reflex at first; however, in most cases, the correct solution is to pass a reference. Read the error and check if ownership is truly necessary.

Why is the borrowing rule so strict?

Because this is the sole cause of data races: one party modifying while another is reading. Since Rust prevents this at compile time, you can write multithreaded code without the fear of deadlock errors. The strictness of the rule eliminates the hardest class of bugs in concurrent programming.

Summary

Every value has a single owner, and when the owner goes out of scope, the value is dropped.

Assignment and function calls move ownership; simple types are copied instead.

There can be a single mutable reference or multiple immutable references at the same time.

A reference to a local value cannot be returned; it is returned as a value.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code