This code won't compile because rust requires a lifetime to be added.
fn firstNoLifetime(x: &str, y: &str) -> &str {
return x;
}
So instead we must add the lifetime explicitly like this:
fn first<'a>(x: &'a str, y: &'a str) -> &'a str {
return x;
}
My question then is, how is it, that this function, without lifetimes, compiles ?
Why are lifetimes not required for generic functions, and are there any caveats around that ?
fn first_generic<A>(x: A, y: A) -> A {
return x;
}
My assumption was that lifetime annotations help the compiler and borrow checker determine the root cause of lifetime violations, but in the code below rust was able to determine the cause without annotations. Is my assumption wrong ? And if so, what is the purpose of lifetime annotations ?
fn first_generic<A>(x: A, y: A) -> A {
return x;
}
fn main() {
let string1 = String::from("long string is long");
let result: &str;
{
let string2 = String::from("xyz");
result = first_generic(string1.as_str(), string2.as_str());
}
println!("The first string is: {}", result);
}
result:
|
10 | result = first_generic(string1.as_str(), string2.as_str());
| ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
11 | }
| - `string2` dropped here while still borrowed
12 |
13 | println!("The first string is: {}", result);
| ------ borrow later used here
where T: 'a
. – LongspurT
doesn't have to be a reference at all. – Longspur&str
type though ? – StockmonT
, including the lifetime. – Longspur