Search code examples
genericsrustlambdareflectionclosures

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


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?
}

Solution

  • 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.