Trying to understand lifetimes in loops

This is absolutely evil. You need to change line 37 to:

Result::Error(_) => panic!("e"),

The key to this is the exact language of the error message:

borrowed value must be valid for the static lifetime...

That confused the hell out of me, because there are no static borrows anywhere in this code. What's actually happening is that when you do panic!(e), you're using e as the literal panic payload. In order for that to work, e itself must live forever. But, Error contains a borrow. So that borrow must live forever.

But the 'a lifetime of that Error borrow is tied to the 'a lifetime in Result. And that lifetime is tied to the lifetime of self, which is in turn the required lifetime of the thing variable.

So thing must be 'static, but it cannot be 'static because it's on the stack.

Boom.

The better solution is to implement Display for Error and then use panic!("{}", e).

Edit: Seriously, this is probably the most baffling borrowing issue I've ever seen. Not only does the error message say something that makes no sense, it doesn't even remotely point at the actual culprit.

13 Likes