Why do I not have to specify a lifetime here? [SOLVED]


#1

Why would I not have to specify a lifetime in the following example? Is it because of lifetime inference (I forget the proper name)?

pub fn at(&self, x: usize, y: usize) -> &Vec<T>{
    &self.data[x][y]
}

My intuition with liftimes tells me I would have to use something more like

pub fn at<'a>(&'a self, x: usize, y: usize) -> &'a Vec<T>{
    &self.data[x][y]
}

Meaning that the reference it returns only lives as long as self, but both examples compile :confused:


#2

These examples are equivalent,because the compiler elides the lifetime of return types to be the same as that of &self.

One example method that might trip you up is this:

pub fn get_suffix(&self, name:&str) -> &str

This desugars to

pub fn get_suffix<'a,'b>(&'a self, name:&'b str) -> &'a str

Edit:
Here is lifetime elision in the book:
https://doc.rust-lang.org/book/second-edition/ch10-03-lifetime-syntax.html#lifetime-elision


#3

Ah, thank you, when I had originally read the book, I mostly skipped the part on lifetimes because they were pretty difficult to understand initially… Thanks alot!