Rust Ownership

www.igif‮moc.aedit‬

Ownership is a key feature of Rust's memory management system. In Rust, each value has a variable that is called its owner. There can only be one owner at a time, and when the owner goes out of scope, the value will be dropped.

Rust's ownership rules are designed to ensure memory safety and prevent common issues such as null pointer dereferencing, use-after-free, and memory leaks. Here are some of the key ownership rules:

  1. Each value has a single owner at any given time.
  2. When a value is assigned to another variable, ownership of the value is transferred to the new variable.
  3. When a variable goes out of scope, the value it owns is dropped.

Here's an example of ownership in action:

let s1 = String::from("hello");
let s2 = s1; // s1's ownership is transferred to s2
println!("{}", s2); // prints "hello"

In this example, we're creating a new String value with the value "hello" and binding it to the variable s1. Then we're assigning s1 to s2, which transfers ownership of the String value to s2. Finally, we're printing the value of s2.

Since ownership of the String value has been transferred to s2, attempting to use s1 after the assignment would result in a compile-time error.

Rust also provides a mechanism for borrowing values without transferring ownership, using references. References allow you to pass a value to a function or method without giving up ownership of the value. Here's an example:

fn print_string(s: &String) {
    println!("{}", s);
}

let s = String::from("hello");
print_string(&s); // pass a reference to s, ownership is not transferred

In this example, we're defining a function called print_string that takes a reference to a String value. We're then creating a new String value with the value "hello" and binding it to the variable s. Finally, we're calling the print_string function with a reference to s, which allows us to pass the value to the function without giving up ownership.

By using ownership and references, Rust's memory management system ensures that memory is handled safely and efficiently, without requiring garbage collection or manual memory management.