Ownership
Introduction
Ownership is the most important feature of Rust. It allows Rust to be memory-safe and efficient, while avoiding garbage collection. Consider the below mistake that all of us who have used a non-GC’d language have made at one point:
fn as_str(data: &u32) -> &str{
// Compute the string
let s = format!("{}", data);
// Oh No! We returned a reference to something that
// only exists in this function.
// Dangling reference! Alas!
return &s;
}
pub fn main(){
let x : u32 = 42;
as_str(&x);
}[quantdev@quasar-arch ownership]$ rustc ./dangling_reference.rs -o ./dangling_reference
error[E0515]: cannot return reference to local variable `s`
--> ./dangling_reference.rs:8:12
|
8 | return &s;
| ^^ returns a reference to data owned by the current function
error: aborting due to 1 previous errorReferences
There are two kinds of references:
- Immutable reference
& - Mutable reference
&mut
which obey the following rules:
- A reference cannot outlive its referent.
- A mutable reference cannot be aliased.
Aliasing
Consider this simple function: