I've been trying to get my head around the Rust borrowing and ownership model.
Suppose we have the following code:
fn main() {
let a = String::from("short");
{
let b = String::from("a long long long string");
println!("{}", min(&a, &b));
}
}
fn min<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() < b.len() {
return a;
} else {
return b;
}
}
min()
just returns a reference to the shorter of the two referenced strings. main()
passes in two string references whose referents are defined in different scopes. I've used String::from()
so that the references don't have a static lifetime. The program correctly prints short
. Here is the example in the Rust Playground.
If we refer to the Rustonomicon (which I appreciate is a work in progress doc), we are told that the meaning of a function signature like:
fn as_str<'a>(data: &'a u32) -> &'a str
means the function:
takes a reference to a
u32
with some lifetime, and promises that it can produce a reference to astr
that can live just as long.
Now let's turn to the signature of min()
from my example:
fn min<'a>(a: &'a str, b: &'a str) -> &'a str
This is more invloved, since:
- We have two input references.
- Their referents are defined in different scopes meaning that they are valid for different lifetimes (
a
is valid longer).
Using similar wording to the quoted statement above, what does the function signature of min()
mean?
The function accepts two references and promises to produce a reference to a
str
that can live as long as the referents ofa
andb
? That feels wrong somehow, as if we return the reference tob
frommin()
, then clearly that reference is not valid for the lifetime ofa
inmain()
.The function accepts two references and promises to produce a reference to a
str
that can live as long as the shorter of the two referents ofa
andb
? That could work, since both referents ofa
andb
remain valid in the inner scope ofmain()
.Something else entirely?
To summarise, I don't understand what it means to bind the lifetimes of the two input references of min()
to the same lifetime when their referents are defined in different scopes in the caller.