PR3-Rust-SS26/H-advanced/lifetime.rs

24 lines
650 B
Rust

// This will give us the Error that string2 did not live long enough
// So that we can find where it happens
// We declare a lifetime named 'a (it can be any letter, but 'a is standard)
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long_string_here");
let result;
{
let string2 = String::from("short");
result = longest(string1.as_str(), string2.as_str());
} // string2 is dropped here
// ERROR: string2 is dead, so result is invalid.
println!("The longest string is {}", result);
}