Showed how to create a lifetime in Rust

main
3008505 2026-06-13 13:17:17 +00:00
parent 65b4d44f7a
commit e461bbf8e6
1 changed files with 24 additions and 0 deletions

View File

@ -0,0 +1,24 @@
// 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);
}