struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn level(&'a self) -> i32 {
3
}
}
vs
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a, 'b> ImportantExcerpt<'a> {
fn level(self: &'b ImportantExcerpt<'a>) -> i32 {
3
}
}
In the example below, your two versions of
level()arelevel_1()andlevel_2().There is not really a difference since these functions return a value, not a reference, thus the subtleties about lifetime do not change anything: the returned value will live on its own.
These two versions are used in the example, and we cannot see any difference about lifetime constraints.
However, if we want to return a reference, as in
text_1()totext_4(), then the lifetimes must be considered with attention.text_1()is the immediate adaptation oflevel_1().The
lifetime elision rulestell us that the lifetime of the resulting&stris that of theselfparameter ('aexplicitly given here).(Note that I'm not certain if it makes sense to write the same lifetime for the structure itself and a reference to it; someone with a better knowledge of Rust than me could develop around that)
This means that the resulting
&strmust not live longer than the structure; this is shown as an error in the example.text_2()is the immediate adaptation oflevel_2().The
lifetime elision rulestell us that the lifetime of the resulting&stris that of theselfparameter ('bexplicitly given here).Then, this is equivalent to
text_3()and the consequence is the same as withtext_1().This means that the resulting
&strmust not live longer than the structure; this is shown as an error in the example.When it comes to
text_4(), we explicitly provide a lifetime for the resulting&strwhich is different from the lifetime of theselfreference.This is actually the same lifetime used internally for
partin the structure.This means that the resulting
&strmust not live longer than the original string used to initialisepart, but it is not at all linked to the structure itself; the example shows that it is still possible to use the resulting&strafter the structure is dropped.