Showed how to create a lifetime in Rust
parent
65b4d44f7a
commit
e461bbf8e6
|
|
@ -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);
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue