This code is based on the example code in the Rust book in the lifetimes chapter. I was wondering how do the following two versions of the same method differ:
struct Important<'a> {
part: &'a str,
}
impl<'a> Important<'a> {
fn larger<'b>(&'b self, other: &'b str) -> &'b str {
if self.part.len() > other.len() {
self.part
} else {
other
}
}
}
versus
struct Important<'a> {
part: &'a str,
}
impl<'a> Important<'a> {
fn larger(&self, other: &'a str) -> &str {
if self.part.len() > other.len() {
self.part
} else {
other
}
}
}
I guess in the first version we are instructing the compiler that
Find a lifetime
'bsuch that both&selfand the referenceotherare valid during it (probably the shorter of the two lifetimes if they overlap)Make sure that the returned reference is only used within that lifetime
'bbecause outside it might become a dangling reference.
What does the second version of the code do? One of the lifetime elision rules in the Rust book says that in a struct method the returned reference is assigned the lifetime of the &self parameter (which is 'a here), so are we saying that other should also be valid for the same lifetime as the &self parameter, which is the lifetime 'a?
Semantically, is this the same code or could these versions behave differently depending of the lifetimes of other and the struct?