Borrowed data escapes outside of my function

which part? if I would guess, you may be lacking deeper understanding of closures.

when you create a closure, although the syntax looks very similar to defining a function, you are actually both defining a data type, and creating a value of the type, at the same time, and you also implement the Fn trait (and/or FnMut, FnOnce, based on the move keyword and code in the body of the "function") for the type. understanding the desugaring of a closure will help you understand the concept of "capture".

you can read the "closure" chapter of the rust book for details, but the short summary is, when you use self inside the closure, the closure must capture it, meaning it must store it as a field (remember a closure is a data type), because self is a reference type with a (non-'static) lifetime, the closure type must also have a lifetime, this violates the 'static bound required by run_interval().

also, I saw this recent post on lower level implementation details of closures, you may find it interesting too.

1 Like