Skip to content

Instantly share code, notes, and snippets.

@misdake
Created May 2, 2022 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misdake/364f00d6d7c43d88b5a5d2e7ba1144b9 to your computer and use it in GitHub Desktop.
Save misdake/364f00d6d7c43d88b5a5d2e7ba1144b9 to your computer and use it in GitHub Desktop.
Rust Lifetime Annotation
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