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
OwnershipBorrowing ( & )
Rust›REFERENCE›Ownership & Borrowing
🔑

Ownership & Borrowing

Rust's signature feature: memory safety.

CommandDescription
OwnershipEvery value has a single owner.
Borrowing ( & )Accessing data without transferring ownership.

Ownership

Try it yourself →

Every value has a single owner.

Syntax

let s2 = s1; // s1 moved

Description

If you assign a value like a String to another variable, ownership is MOVED; the old variable can no longer be used. This prevents memory errors at compile time.

Example

fn main() {
    let s1 = String::from("Alex");
    let s2 = s1;
    println!("{}", s2);
}

Expected output

Alex

When to use?

Memory safety (without a garbage collector).

Common mistakes

  • ⚠️ Using the old variable after a move is an ERROR: s1 is now invalid.

Borrowing ( & )

Try it yourself →

Accessing data without transferring ownership.

Syntax

fn name(x: &String) { }

Description

You BORROW a value with &; ownership is not moved, and it can continue to be used. A way to pass large data to functions without copying.

Example

fn length(s: &String) -> usize {
    s.len()
}
fn main() {
    let s = String::from("Hello");
    println!("{}", length(&s));
    println!("{}", s);
}

Expected output

5
Hello

When to use?

Passing data to a function without copying.

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