Skip to content

Instantly share code, notes, and snippets.

@bluecmd
Last active September 4, 2022 10:08
Show Gist options
  • Save bluecmd/6e2b18f3e6fdf0515206b7b01df7496a to your computer and use it in GitHub Desktop.
Save bluecmd/6e2b18f3e6fdf0515206b7b01df7496a to your computer and use it in GitHub Desktop.
Rust Lifetime question
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn min_length_string(x: &str) -> &str {
// Why does this not violate the lifetime checker?
// Isn't it dropped in with this stack frame?
// Answer: https://doc.rust-lang.org/nightly/rust-by-example/scope/lifetime/static_lifetime.html
let string2: &str = "too short";
return longest(x, string2);
}
fn main() {
let string1 = String::from("hello");
let result = min_length_string(string1.as_str());
println!("The string is '{}'", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment