Skip to content
This repository has been archived by the owner on Sep 30, 2020. It is now read-only.

FAQ: update information on returning closures #1121

Open
FranklinChen opened this issue Jun 3, 2018 · 2 comments
Open

FAQ: update information on returning closures #1121

FranklinChen opened this issue Jun 3, 2018 · 2 comments

Comments

@FranklinChen
Copy link

This replaces rust-lang/rust#51289

The closure must also be wrapped in a Box, so that it is allocated on the heap.

at https://www.rust-lang.org/en-US/faq.html#how-do-i-return-a-closure-from-a-function is no longer correct because now it is possible to return a closure without boxing it thanks to the ability to return impl Trait as of rust-lang/rust#49255

@est31
Copy link
Member

est31 commented Jun 3, 2018

It should probably also mention that if the closure doesn't capture anything, you can return a function pointer now, as non capturing closures coerce to function pointers.

@A1-Triard
Copy link

A1-Triard commented Sep 10, 2019

now it is possible to return a closure without boxing it thanks to the ability to return impl Trait

But it is not possible:

trait SomeTrait { }

trait SomeTraitExt : SomeTrait {
    fn return_closure() -> impl Fn() {
        || { }
    }
}

impl SomeTraitExt for SomeTrait { }

gives

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
 --> src/main.rs:4:28
  |
4 |     fn return_closure() -> impl Fn() {
  |                            ^^^^^^^^^

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants