when rust lifetimes finally click

11 July 2020. Estimated reading time: 2 min.

I started learning Rust by reading the Book, cover to cover. Lifetimes were far from the hardest topic for me to get used to, and I even took care to make a mental note that

Lifetime annotations don’t change how long any of the references live.

So I was very surprised to realize that, a few days layers, I had no idea what my custom error types were supposed to return when implementing Error::source.

fn source(&self) -> Option<&(dyn Error + 'static)>;

Let's try to translate this: source returns an Option over a reference to a trait object that implements the Error trait and has static lifetime.

Option and reference, fine. I have to admit I'd already forgotten about trait objects (I could remember why they were necessary, not their syntax or name), but they were easy to look up.

However, doesn't 'static means that the value has to live until the program ends? Aren't constants the things with static lifetimes?

First, no. Second, constants have static lifetimes, but aren't the only things that do.

A static lifetime means a value that may live indefinitely, if required to. And the most common values with static lifetimes are... owned values, unless they explicitly depend on other values with shorter lifetimes.

So the returned value from source can be understood as an Option over a reference to an Error-like value, that either owns all their memory or that is otherwise guaranteed to live for as long as it is necessary.

This is what made lifetimes finally click to me. I think...

By the way, I discovered that owned values are 'static in a reply on the Rust discord logs; other people have gotten stuck on Error + 'static trait objects.

Last updated: 17 July 2020.