See video 12: Lifetimes
When a function returns a reference, the lifetime can be “elided” (left out) if:
&self or &mut self// Returns Data that is valid forever
fn data() -> &'static Data
// Returns Data owned by *x
fn get_data(x: &🟥mut? Foo) -> &🟥mut? Data
// Returns Data that is valid forever
fn lookup_data(x: &Foo) -> &'static Data
// Returns Data owned by *x
fn from_x<'a>(x: &'a mut? Foo, y: &mut? Bar) -> &'a mut? Data
// Returns Data owned by *y
fn from_y<'a>(x: &mut? Foo, y: &'a mut? Bar) -> &'a mut? Data
// Returns Data that might be owned by *x or *y
fn either<'a>(x: &'a mut? Foo, y: &'a mut? Bar) -> &'a mut? Data
// Returns Data that is valid forever
fn neither(x: &mut? Foo, y: &mut? Bar) -> &'static Data
impl Map {
// Returns Data owned by *self
fn get(&🟥mut? self, key: &Key) -> Option<&🟥mut? Data>
// Returns Data owned by *self or *other
fn get_or<'a>(&'a mut? self, other: &'a mut? Bar) -> &'a mut? Data
}
impl Key {
// Returns Data owned by *map
fn lookup_in<'a>(&self, map: &'a mut? Map) -> &'a mut? Data
}
struct Product {
data: &'static Data,
}
struct Book<'a> {
title: &'a str,
author: &'a str,
}
impl<'a> Book<'a> {
// Returns a reference that outlives self
fn title(&self) -> &'a str
}
struct OccupiedEntry<'a> {
map: &'a mut Map,
index: usize,
}
impl<'a> OccupiedEntry<'a> {
// Returns Data owned by the Map
fn get(&🟥self) -> &🟥Data
// Returns Data owned by the Map (borrowed via self)
fn get_mut(&🟥mut self) -> &🟥mut Data
// Consumes self, returns a reference that outlives self
fn into_mut(self) -> &'a mut Data
}
T: 'static means T does not borrow. T must not have any lifetime constraints, so a value of type T can be held indefinitely.
T: 'a means if T is a reference or contains a reference, it must be valid for at least 'a.
'b: 'a means 'b must be valid for at least 'a.