Ownership and Moving
It’s time to introduce one of the most core concepts in all of Rust: ownership. We’ll discuss the motivation for this another time, but every value in Rust has exactly one owner. For example, in this program:
fn main() {
let x: i32 = 5;
println!("{}", x);
}
The x
variable points to the value 5, and the value 5 is owned by the main
function. Blocks can also be owners. So, for example:
fn main() {
{
let x: i32 = 5;
println!("{}", x);
}
}
main
owns that block, and the block owns the value 5. Values can even own other values. Our fruit
value we created owns the 10 and 5 in the apples
and bananas
fields.
Let’s take a look at our broken program again: