Skip to content

Instantly share code, notes, and snippets.

fn nested_borrow_outlives_value() {
let value = "abc".to_string(); // crate value
let borrow = &value; // create borrow
// with lifetime of value
let my_box = Box::new(borrow); // create my_box
// with lifetime of borrow,
// which is lifetime of value
return my_box // <COMPILE TIME FAIL>
// my_box is not deleted,
// but value is deleted,
fn value_moved_during_borrow_lifetime() {
let value = "abc".to_string(); // crate value
let borrow = &value; // create borrow
let my_box = Box::new(value); // <COMPILE TIME FAIL> move of value
// while borrowed
}
fn borrow_outlives_value() -> &String {
let value = "abc".to_string(); // crate value
let borrow = &value; // create borrow
return borrow // borrow is not deleted
// <COMPILE TIME FAIL> delete value,
// but it's still borrowed
}
fn valid_flow() {
let value = "abc".to_string(); // crate value
let borrow = &value; // create borrow
println!("{}", value); // use value without moving it
println!("{}", borrow); // use borrow
// delete borrow
// delete value safely, because
// it's no longer borrowed
}
struct MyStruct { // structure definition
my_box: Box<u32>, // it has only 1 field,
// a Box keeping integer on heap
}
fn my_fn() {
let my_struct = MyStruct { // create instance of structure
my_box: Box::new(1234), // acquire memory
};
println!("{}", my_struct.my_box); // use
fn my_fn() {
let my_box = Box::new(1234); // acquire
println!("{}", my_box); // use
// delete my_box,
// which releases memory
}
main {
A = allocate() // A's lifetime begins
do_stuff(A) // use A
B = A // B's lifetime begins
do_stuff(B) // use B
release(A) // release, A's and B's lifetimes end
do_stuff(A) // <RUN TIME FAIL> use A after its lifetime ended
do_stuff(B) // <RUN TIME FAIL> use B after its lifetime ended
}
main {
A = allocate() // acquire
do_stuff(A) // use
release(A) // release, pointer owns allocation
// delete pointer
}
do_stuff(B) {
do_more_stuff(B) // use
// don't release, pointer doesn't own allocation
main {
...
A = <pointer to>──────┐
... |
} │
╔══ HEAP ALLOCATED ════════╗
║ AA = "reachable" ║
║ AB = <pointer to>──────┐ ║
╚════════════════════════│═╝
main {
A = allocate() // acquire
do_stuff(A) // use
release(A) // release
release(A) // <RUN TIME FAIL> release invalid pointer
// delete pointer
}