Skip to content

Instantly share code, notes, and snippets.

@deepu105
Created March 30, 2020 17:54
Show Gist options
  • Save deepu105/681462673576bea16802c74252867323 to your computer and use it in GitHub Desktop.
Save deepu105/681462673576bea16802c74252867323 to your computer and use it in GitHub Desktop.
Rust ownership and lifetimes
// This function takes ownership of the passed value
fn take_ownership(value: Box<i32>) {
println!("Destroying box that contains {}", value); // value is destroyed here, and memory gets freed
}
// This function borrows the value by reference
fn borrow(reference: &i32) {
println!("This is: {}", reference);
}
fn main() {
// Allocate an integer on the heap
let boxed = Box::new(5_i32); // Value is owned by `boxed` | Lifetime of `boxed` starts
// Allocate an integer on the stack
let stacked = 6_i32; // Value is owned by `stacked` | Lifetime of `stacked` starts
// Borrow the contents of the box. Ownership is not taken, so the contents can be borrowed again.
borrow(&boxed); // Value is still owned by `boxed` and a reference is passed
borrow(&stacked); // Value is still owned by `stacked` and a reference is passed
{
// Take a reference to the data contained inside the box
let ref_to_boxed: &i32 = &boxed; // Value is still owned by `boxed` | Lifetime of `ref_to_boxed` starts
// Take a copy of the value on stack
let copy_of_stacked: i32 = stacked; // Copied value is owned by `copy_of_stacked`, original value is owned by `stacked` | Lifetime of `copy_of_stacked` starts
// Allocate a string on the heap
let boxed_2 = Box::new("Hello"); // Value is owned by `boxed_2` | Lifetime of `boxed_2` starts
// Borrow `ref_to_boxed`
borrow(ref_to_boxed); // Value is still owned by `boxed`
// `ref_to_boxed` goes out of scope and is no longer borrowed.
// `copy_of_stacked` and `boxed_2` is destroyed here, and memory gets freed
//Lifetime of `ref_to_boxed`, `copy_of_stacked` and `boxed_2` ends
}
// `boxed` is now moved and hence ownership changes
take_ownership(boxed); // Value is now owned by `take_ownership`
// `boxed` is destroyed inside `take_ownership`, and memory gets freed
// `stacked` is destroyed here, and memory gets freed
//Lifetime of `boxed` and `stacked` ends
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment