├── Cargo.toml ├── Cargo.lock └── src └── main.rs /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sandbox-rust-lifetimes" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "sandbox-rust-lifetimes" 7 | version = "0.1.0" 8 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | 5 | //=============================== 6 | // TYPES 7 | //=============================== 8 | 9 | // a struct with a lifetime annotation 10 | struct Car<'a> { 11 | model: &'a str 12 | } 13 | 14 | //=============================== 15 | // FUNCS 16 | //=============================== 17 | 18 | // in this example, the compiler will error is you uncomment the print 19 | fn dangling_reference() { 20 | let r; 21 | { 22 | let x = 5; 23 | r = &x; 24 | } 25 | // println!("{}", r); 💥 Dangling reference! 26 | } 27 | 28 | // in this example, we have a function which returns a reference with annotated lifetimes 29 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { 30 | if x.len() > y.len() { 31 | x 32 | } else { 33 | y 34 | } 35 | } 36 | 37 | // in this example, we use a lifetime within a trait bound 38 | fn print_with_lifetime<'a, T>(item: &'a T) 39 | where 40 | T: std::fmt::Display + 'a, 41 | { 42 | println!("{}", item); 43 | } 44 | 45 | 46 | --------------------------------------------------------------------------------