Rust Tutorial
Estimated reading: 4 minutes 26 views

🦀 Rust – Ownership, Borrowing & Slices: Mastering Memory Safety

🧲 Introduction – Why Learn Ownership, Borrowing & Slices in Rust?

Rust’s biggest innovation is its memory management system. It avoids garbage collection by enforcing ownership, borrowing, and slicing rules at compile time. These features help you write safe, concurrent, and performant programs—without memory leaks or race conditions.

🎯 In this guide, you’ll learn:

  • What ownership means and how it works
  • How borrowing prevents unsafe data access
  • What slices are and how they avoid copying
  • Practical examples with output and detailed explanations

🔐 Ownership in Rust

In Rust, every value has a single owner, and ownership can be moved or transferred, not copied by default.

🔹 Code Example:

fn main() {
    let s1 = String::from("hello");
    let s2 = s1;
    println!("{}", s2);
    // println!("{}", s1); // ❌ This will cause a compile-time error
}

🧠 Explanation:

  • let s1 = String::from("hello");s1 owns the String.
  • let s2 = s1; → Ownership is moved to s2; s1 is now invalid.
  • Accessing s1 afterward causes a compile-time error.

📤 Output:

hello

⚠️ Rust prevents double frees by invalidating the original owner after the move.


♻️ Cloning to Copy Data

To clone data instead of moving ownership, use .clone().

🔹 Code Example:

fn main() {
    let s1 = String::from("Rust");
    let s2 = s1.clone();

    println!("s1: {}, s2: {}", s1, s2);
}

📤 Output:

s1: Rust, s2: Rust

🤝 Borrowing in Rust (&)

Borrowing allows functions or code to access data without taking ownership.

✅ Immutable Borrowing

fn print_msg(msg: &String) {
    println!("Message: {}", msg);
}

fn main() {
    let text = String::from("Borrowed string");
    print_msg(&text);
    println!("Original: {}", text); // Still valid
}

🧠 Explanation:

  • &String creates a borrowed reference.
  • text is passed without losing ownership.

📤 Output:

Message: Borrowed string
Original: Borrowed string

🔒 Mutable Borrowing (&mut)

fn update(s: &mut String) {
    s.push_str(" updated");
}

fn main() {
    let mut text = String::from("Text");
    update(&mut text);
    println!("{}", text);
}

📤 Output:

Text updated

📌 Only one mutable reference is allowed at a time—Rust prevents data races.


🚫 Borrowing Rules Summary

RuleWhy it Exists
Only one mutable reference at a timePrevents race conditions
Or many immutable referencesAllows safe concurrent reads
No simultaneous mutable & immutablePrevents conflict between readers/writers

🧩 Slices in Rust

Slices let you reference part of a collection (like arrays or strings) without copying.

🔹 Code Example:

fn main() {
    let greeting = String::from("hello world");
    let hello = &greeting[0..5];
    let world = &greeting[6..];

    println!("{} {}", hello, world);
}

🧠 Explanation:

  • &greeting[0..5] → Slices "hello"
  • &greeting[6..] → Slices from index 6 to end

📤 Output:

hello world

⚠️ Common Mistakes in Ownership and Borrowing

MistakeError/WarningFix
Using value after moveCompile-time errorUse .clone() or refactor to borrow
Mutable and immutable borrow comboConflict detected by compilerSeparate scopes or refactor logic
Holding reference beyond valid scope“borrow may be used after free” errorLimit lifetimes or restructure logic

📌 Summary – Recap & Next Steps

Ownership, borrowing, and slicing are the foundation of Rust’s memory model. They ensure memory safety without garbage collection, empowering you to build efficient and race-free applications.

🔍 Key Takeaways:

  • Ownership transfers data control; values are invalidated after move
  • Borrowing gives access without transferring ownership
  • Only one mutable or many immutable references allowed at once
  • Slices offer efficient access to parts of collections

⚙️ Next: Dive into Rust – Arrays, Vectors & Tuples to explore common data structures using these principles.


❓FAQs


What is ownership in Rust?
✅ Ownership means each value has a single owner. When ownership is moved, the previous owner is invalidated.


How do I pass data without transferring ownership?
✅ Use borrowing (&T) to pass by reference. For modification, use &mut T.


Why does Rust restrict multiple mutable references?
✅ To avoid data races and ensure memory safety at compile time.


What is the difference between slice and borrowing?
✅ A slice is a specific form of borrowing that refers to part of a collection (like a substring or sub-array).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust Ownership, Borrowing & Slices

Or Copy Link

CONTENTS
Scroll to Top