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:
s1
initially owns the memory containing the string"Hello"
.- When you assign
s1
tos2
, Rust moves ownership of the memory froms1
tos2
. - After this move,
s1
becomes invalid—it's no longer allowed to access the data because ownership has transferred.
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:
- Allocating new memory.
- Copying each byte into this new space.
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.