by sakisv · 11mo ago · 0 comments
What I _do_ find annoying though and I cannot wrap my head around are lifetimes. Every time I think I understand it, I end up getting it wrong.
I believe your parent is implying that if you skip using a lifetime and do something else instead to make it easier, that may be less performant.
struct MyRef<'a> { item: &'a i64 }
struct MyType { items: Vec<i64> }
impl MyType {
fn get_some_ref(&self, key: &usize) -> MyRef<'a> {
MyRef { item: &self.items[key] }
}
}
the function this way is incorrect. When I was a beginner, I would have thought that every & in the signature needed a lifetime. In a slightly complicated code, the borrow checker then demanded lifetimes everywhere, they'd infect everything, but the code would still never compile.Then I understood that not everything needs to be tied to the same lifetime. In this example, MyRef should be tied to the MyStruct, but not to the `key`:
fn get_some_ref<'a>(&'a self, key: &usize) -> MyRef<'a>