Lazy evaluation of closures



In my crate there is some validation code similar to this example. I would like to make the evaluation of path lazy, that is, to ensure path is only constructed when an error actually occurs and not during every call to validate().

In the implemenation of Validate::lazy in the example, is it guaranteed that path will in fact be lazily evaluated as described?

The actual validation code I’m referring to is sitting here but uses the eager version from the example.


Yes, it’ll be lazy. Specifically, the body of the lambda will run lazily; the creation of a struct that the compiler generates to desugar the lambda is eager.


Thanks for your reply; that answers my question.

My only remaining concern is whether it’s cheaper to create these compiler generated structs than it is to create the strings. That’s something for me to investigate, I guess.


It’s almost surely cheaper, as the struct will be created directly without any heap allocation.


As @cuviper mentioned, it’ll be cheaper both in terms of CPU cycles and also heap allocator pressure (since it’ll be on the stack). Moreover, the compiler may inline through your entire call chain and then flat out remove the struct allocation altogether, and just replace its uses with the scalar values directly.


Great, that’s exactly what I wanted to hear. Thanks for clarifying.