Possible to define generic closure?

后端 未结 2 1152
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 18:13

Does Rust support closures with generic return types? For example, I want to write something like this:

let get = |s: &str| -> Opt         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-07 18:39

    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, 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 = ... 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 |s: &str, t: T| {...}
    

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

提交回复
热议问题