Closed
Description
Generic lifetimes in functions says:
(...) [the] return type needs a generic lifetime parameter on it because Rust can’t tell whether the reference being returned refers to
x
ory
.
The code snippet is:
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}
This example would be enhanced with context afterwards:
fn main() {
let result: &str;
let x = "hi";
{
let y = String::from("world");// freed at end of block
result = longest(x, y.as_str());
}
// now result is a dangling pointer
println!("{result}");
}
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}
This would provide an easier understanding of why the lifetime matters. To an extent you have provided this example at the beginning (without a function) but the context seems to matter a lot here as well.
Interestingly, the example passes using static strings, since those live "forever". Which was 🍭 so confusing to me as well 🍭
cc @StefanSalewski, @carols10cents. In case you have an opinion.
Metadata
Metadata
Assignees
Labels
No labels