> Hopefully the setup of closures that probably won't be executed isnt't too expensive. Do those require a heap allocation and release when not used, or is this all on the stack?
Creating a closure with |...| { ... } is literally as expensive as creating a tuple containing (references to) the variables it captures. That is, they're on the stack by default like everything else in Rust, and there's no implicit heap allocations. For more details, see, for instance, http://huonw.github.io/blog/2015/05/finding-closure-in-rust/ .
> Rust has no idea which closure a function will call, if any.
It does. As my link above discusses, each closure has a unique type, allowing monomorphisation to kick in and hence the compiler can easily optimise and inline calls to closures (as long as the author of the closure-taking function doesn't opt-in to only allowing virtual dispatch).
Creating a closure with |...| { ... } is literally as expensive as creating a tuple containing (references to) the variables it captures. That is, they're on the stack by default like everything else in Rust, and there's no implicit heap allocations. For more details, see, for instance, http://huonw.github.io/blog/2015/05/finding-closure-in-rust/ .
> Rust has no idea which closure a function will call, if any.
It does. As my link above discusses, each closure has a unique type, allowing monomorphisation to kick in and hence the compiler can easily optimise and inline calls to closures (as long as the author of the closure-taking function doesn't opt-in to only allowing virtual dispatch).