sasha.computer

ownership in rust super simple edition

Let's break down Rust's concept of ownership with a simple example:

fn main() {
    let s1 = String::from("Hello"); // s1 owns "Hello"
    let s2 = s1; // Ownership moves from s1 to s2

    // println!("{}, world!", s1); // Error: s1 no longer valid after ownership moved
    println!("{}, world!", s2); // Valid, prints "Hello, world!"
}

Here's what's happening:

Why doesn't Rust just copy the data?

In many languages, assigning variables creates a copy by default. In Rust, this kind of implicit copying (known as a deep copy) would be expensive because it involves:

Rust avoids these hidden costs by making such operations explicit:

let s1 = String::from("Hello");
let s2 = s1.clone(); // Explicit deep copy

println!("{}, {}", s1, s2); // Valid, prints "Hello, Hello"

By requiring .clone(), Rust ensures you're aware of the performance trade-offs you're making.

In short, ownership in Rust provides memory safety without sacrificing performance, but it requires you to be explicit about costly operations like copying.