In Rust, how to inspect values captured by a closure?

46 Views Asked by At

In Rust, how can I create a function accpeting a closure as argument that iterates and prints all values captured by the closure reflectively?

For example:

fn print_captured_values<F>(f: F) where F: Fn() {
  // How to implement it?
}
1

There are 1 best solutions below

2
kmdreko On

You cannot.

Closures have anonymous opaque types and only implement the Fn* traits (and auto traits) they can. Rust does not have reflection and it's reflection-like mechanisms aren't possible on non-local types.