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