🦀 Rust - Ownership
Ownership
Updated at 2024-01-04 06:26
Rust deletes all values that are not owned by a variable; and variables disown their values when they go out of scope.
This might be familiar for C programmers, but in a nutshell:
- Your program lives in a stack, starting from the
mainfunction. - Each scope, like a function, creates a stack frame.
- You can only directly access things in your current stack frame.
- You can only add things to stack that have a fixed, known size like
i8. - If you need something more dynamic like a
String, Rust needs to place that value to the heap and add a fixed size reference to that value to the stack. - The heap grows dynamically as needed.
Each value in Rust has a single owner; that is "the variable" in the code. When the value's owner (variable) goes out of scope, the value will be dropped from memory.
fn main() {
let x = 11;
let y = x; // creates an implicit COPY for value 11 in the stack
assert_eq!(x, y); // _the values_ are equal
assert_ne!(&x as *const i32, &y as *const i32); // _the references_ are not
assert_eq!(&x as *const i32, &x as *const i32);
}
fn main() {
let a = String::from("bomb");
transfer_ownership(a);
// assert_eq!(a, "bomb"); // would crash as the ownership was passed down
let b = String::from("tomb");
let bb = return_ownership(b);
assert_eq!(bb, "tomb"); // works because ownership was returned
// usually you would BORROW the value:
let c = String::from("womb");
borrow_string(&c);
assert_eq!(c, "womb");
// you can also have a single mutable borrow:
let mut d = String::from("comb");
mutable_borrow_string(&mut d);
assert_eq!(d, "");
}
fn transfer_ownership(s: String) {
assert_eq!(s, "bomb");
}
fn return_ownership(s: String) -> String {
assert_eq!(s, "tomb");
s
}
fn borrow_string(s: &String) {
assert_eq!(s, "womb");
}
fn mutable_borrow_string(s: &mut String) {
assert_eq!(s, "comb");
s.clear();
assert_eq!(s, "");
}