Possible to define generic closure?

No, AFAIK you can’t. I mean, you can define a generic closure, what you can’t do is create a let binding with a generic left-hand side.

A fn get<T>, as the one you mention rewriting, undergoes monomorphisation, i.e. when compiling it, rustc generates a different version of get for every actual T that is used to call it. By the time you assign the result of that get (let a = get(...)), that result has a concrete type and size.

A let binding does not get monomorphised, so you can’t have a let a<T> = ... and have a different version of a generated for you by the compiler.

What I think might enable this is the introduction of higher-kinded types, which is one of the highly desired but not yet fully fleshed out new features for Rust. They would enable you to write something like:

// does not work as of Rust 1
let a = for<T> |s: &str, t: T| {...}

i.e. return a closure that I can later parametrize with a T (which is what you’re asking for).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)