Dangling References Prevented at Compile Time
Dangling References Prevented at Compile Time
In languages with manual memory management, creating a pointer to memory that has been deallocated results in a dangling reference. Rust guarantees this never occurs:
// Attempting to return a reference to a local variable:
// fn dangle() -> &String {
// let s = String::from("temporary");
// &s // ERROR: `s` does not live long enough
// }
// The idiomatic solution: transfer ownership of the value itself
fn no_dangle() -> String {
let s = String::from("valid data");
s
}
fn main() {
let result = no_dangle();
println!("Received: {}", result);
}