Lifetimes
Last updated
Last updated
Lifetimes are a way to manage and ensure memory safety by defining the scope for which a reference is valid.
Prevent dangling references and ensure that references don't outlive the data they point to.
Lifetime are denoted using ('
) followed by a name, like 'a
.
Most of the time, we don't need to explicitly annotate lifetimes because Rust has lifetime elision rules to infer lifetimes in simple cases.
References:
This exercise is a bit easy.
Rust cannot infer the lifetime of input reference in function longest
.
So we need to define lifetime explicitly by adding 'a
(you can change the lifetime name with anything you want).
This is to bind the lifetime of input x
and y
into the output of longest
function.
This exercise is easy.
The println
macro is using result
variables which already out of scope (rust already drop it) so we cannot access it anymore.
We just need to move the line to inside the bracket.
In this exercise we have struct Book
that hold a reference.
So we ned to explicitly define lifetime of each reference in the struct so the struct doesn't outlive the reference.
We can do it like this: