Ownership and Reference
Ownership is for managing heap data.
- Each value in Rust has a variable that’s called its owner.
- There can only be ==one owner== at a time.
- When the owner goes out of scope, the value will be ==dropped==.
References and borrowing
&references doesn't get ownership, so it's just borrowing.References with
mut, to prevent data race, Rust only allow one mutable reference on a scope. Also we cannot have a mutable reference while we have an immutable one in ==using==.let mut s = String::from("hello");
let s1 = &mut s;
let s2 = &mut s; // wrong
let r1 = &s; // no problem
let r2 = &s; // no problem
let r3 = &mut s; // wrong
println!("{}, {}, and {}", r1, r2, r3);
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{} and {}", r1, r2);
// r1 and r2 are no longer used after this point
let r3 = &mut s; // no problem
println!("{}", r3);Dangling References
fn dangle() -> &String {
let s = String::from("hello");
&s // wrong, s will be deallocated
}
fn no_dangle() -> String {
let s = String::from("hello");
s // ok, string ownership is moving out
}
Questions
Is there any way to retuen a reference to a variable declared in a function?
No. Just return an owned object instead of a reference, or set a reference as function arguments.