Rust Tutorials: Ownership Rules 🎯

beginner
11 min

Rust Tutorials: Ownership Rules 🎯

Welcome to the Ownership Rules tutorial! In this comprehensive guide, we'll dive deep into the fundamental ownership rules of Rust, a powerful, modern programming language designed for high performance. Let's get started!

What are Ownership Rules? πŸ“

Ownership Rules in Rust are a set of rules that manage memory allocation and deallocation automatically. They ensure that resources are always properly allocated, used, and freed, reducing the chances of memory leaks and other common errors.

The Three Core Ownership Rules πŸ’‘

  1. Each value in Rust has a variable that’s called its owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped and the memory it occupies will be freed.

Let's take a look at some examples to better understand these concepts:

rust
fn main() { let s = String::from("hello"); // variable `s` owns the String // The variable `s` goes out of scope here and the String is dropped. }

In the example above, the variable s is the owner of the String. When the main function finishes execution, the s variable goes out of scope, and the String it owned is dropped, and the memory it occupied is freed.

Ownership and Data Structures πŸ“

Rust has a unique system to handle complex data types like structs and arrays. The entire data structure is treated as a single unit, and all its parts are owned by the variable that holds the data structure.

rust
struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 0, y: 0 }; // the variable `p` owns the Point struct }

In this example, the variable p owns the Point struct, and both the x and y variables inside the struct are part of the owned data.

Borrowing and Lifetimes πŸ’‘

Borrowing allows us to use values owned by other variables without taking ownership. This is crucial when we want to work with multiple references to the same data. Lifetimes ensure that these references don't outlive the data they refer to.

Here's an example of borrowing:

rust
fn main() { let s = String::from("hello"); // Borrowing `s` as a reference let len = s.len(); // The variable `s` goes out of scope here, but it's still being used by the `len` variable. // No panic occurs because Rust knows about the reference and the lifetime of the data it refers to. }

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

Which of the following is NOT a core ownership rule in Rust?

That's it for this tutorial on Ownership Rules! In the next lesson, we'll dive deeper into Rust's borrowing and lifetimes, and learn how to safely work with references to shared data. Stay tuned! πŸš€