// this function foo
fn foo(s: &str) -> &str {
&s[0..1]
}
// is equivalent to this function
fn foo_desugared<'a>(s: &'a str) -> &'a str {
&s[0..1]
}
// this works too because the lifetime of "" is 'static because
// it is a str that lives in the .data segment, which will live for "any 'a"
fn bar(s: &str) -> &str {
&""
}
fn main() {
// as shown here
bar(&String::new());
}
// but this won't work, because `x` gets `drop`ed at the end of `baz`
fn baz(x: &str) -> &str {
let x = String::new();
&x
}
Keep in mind that lifetimes have the opposite behavior of generic types. A T: Trait type parameter means "something that implements at least Trait, but might implement other things that you won't have access to", while an &'a returned borrow means "something that lives at least up to 'a, but might live less".
>Keep in mind that lifetimes have the opposite behavior of generic types. A T: Trait type parameter means "something that implements at least Trait, but might implement other things that you won't have access to", while an &'a returned borrow means "something that lives at least up to 'a, but might live less".
I don't know what you're trying to say here, but taken at face value it is wrong, and your own `fn bar` example demonstrates it being wrong. "something that lives at least up to 'a but might live less" is a contradiction.
Perhaps you meant "... but might live longer" ? If so, it would be correct, and also would not be "the opposite behavior of generic types."
calling `let z = foo(y);` is valid. The lifetime of `y` conforms to the lifetime of `x` in the `foo` signature, while the lifetime of `z` can be as long as the one for `x` (up to x's lifetime), but it is shorter (unless you try to do `drop(y)`, which would be a borrow checker error).
Keep in mind that lifetimes have the opposite behavior of generic types. A T: Trait type parameter means "something that implements at least Trait, but might implement other things that you won't have access to", while an &'a returned borrow means "something that lives at least up to 'a, but might live less".