Why can lifetimes not be inferred?

First of all, as a co-author of the book, thank you!

Second, I think there’s a deeper reason here that’s being missed. Yes, Rust could look at function bodies and infer lifetimes. Not doing so is a choice. The reason is the same reason we don’t infer the types of functions (lifetimes are types!). Rust views the function signature as the holy contract, and the body is expected to follow it. If we inferred the signature, changing the body could change the type. And if that happened, you could create breaking changes without realizing it. You also would get far worse error messages, as the error would be in the caller of the functions, not the line you changed in the body. Does that make sense?

16 Likes