From e461bbf8e6da361d3ab04d7abfd86623851a7b5f Mon Sep 17 00:00:00 2001 From: 3008505 <3008505.studs.hs-mannheim.de> Date: Sat, 13 Jun 2026 13:17:17 +0000 Subject: [PATCH] Showed how to create a lifetime in Rust --- H-advanced/lifetime.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 H-advanced/lifetime.rs diff --git a/H-advanced/lifetime.rs b/H-advanced/lifetime.rs new file mode 100644 index 0000000..f7db635 --- /dev/null +++ b/H-advanced/lifetime.rs @@ -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); +} \ No newline at end of file