Created
May 2, 2022 02:34
-
-
Save misdake/364f00d6d7c43d88b5a5d2e7ba1144b9 to your computer and use it in GitHub Desktop.
Rust Lifetime Annotation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn select_u32<'a>(a: &'a u32, b: &'a u32, select_a: &'a bool) -> &'a u32 { | |
if *select_a { a } else { b } | |
} | |
const STR_A: &'static str = "A"; | |
const STR_B: &'static str = "B"; | |
fn select_str(s: &str) -> &str { | |
if s.is_empty() { STR_A } else { STR_B } | |
} | |
fn main() { | |
let a: u32 = 1; | |
let b: u32 = 2; | |
let mut select_a: bool = true; | |
let r = select_u32(&a, &b, &select_a); | |
select_a = false; //won't compile | |
println!("select_u32: {}", r); | |
let mut s: String = String::new(); | |
let selected = select_str(s.as_str()); | |
s = String::from("!"); //won't compile | |
println!("select_str: {}", selected); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment