I have been batteling lifetimes. If I am going to use Rust to its potential I need to come to terms with them.
I get the concept, I see what they are for but the syntax escapes me completely. There is a lot of what look like "magic incantations" to me that serve no purpose. I trust the writers of the rust compiler, the fault is mine.
Reading the chapter in TRPL leaves my with some questions about life times.
(1)
In the following example programme (from the book)....
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long string is long");
{
let string2 = String::from("xyz");
let result = longest(string1.as_str(), string2.as_str());
println!("The longest string is {}", result);
}
}
What is the point of the declaration of the lifetime 'a in angle brackets?
fn longest<'a>... It serves no visible purpose as...
fn longest(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
...is unambiguous
(2)
Is there ever a case....
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
}
Where there are two distinct life times here? E.g:
impl<'a> ImportantExcerpt<'b> {
fn level(&self) -> i32 {
3
}
}
If not, why declare 'a twice?
In fact, why declare it at all? In what circumstance would leaving out the declaration make the syntax ambiguous?
(3)
In this case why are life time declarations needed at all? The declared life time is not used
impl<'a> ImportantExcerpt<'a> {
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
self.part
}
}