Lifetimes and no memory corruption guarantees

It's impossible to use a reference when its target doesn't exist anymore. The only time you'd need to make sure not to mess up your lifetimes for your program not to violate memory safety is when you are using unsafe code blocks. In your example you don't use unsafe, thus if you get the lifetimes wrong the code won't compile anymore.

I need to clarify my last statement a bit as it sounds like “wrong” lifetimes are always compiler errors and the Rust compiler always knows which lifetime annotations you need to write. To the point that people are wondering why you need to annotate lifetimes at all and why the compiler is annoyingly hesitating in telling you the correct lifetimes even if it ought to already know them.

The compiler doesn’t already know the correct lifetimes for every function in advance and it is still possible to get lifetime annotations wrong (in unsafe-free code), but never in a way that compromises memory safety. They can be wrong in the sense that they are not general enough, the consequence would be that your API becomes hard or impossible to use. It is not any memory-corrupting runtime-errors you need to worry about when writing lifetime annotations but the compile-time errors that users of your code might get. When you are your own user, this means that the compiler could complain about the code near the use site of a function while the real (and actually fixable) error was made in the lifetime annotations of the definition of that function.

In your example code, you could just try to mess up the lifetimes yourself and see when you’ll get a compile error. No need to ask anybody about what the compiler will tell you when you can ask the compiler yourself.

3 Likes