rust-lang / prev.rust-lang.org

The previous Rust website. The current website's code is at https://github.com/rust-lang/www.rust-lang.org.
https://prev.rust-lang.org
Apache License 2.0
151 stars 340 forks source link

FAQ: update information on returning closures #1121

Open FranklinChen opened 6 years ago

FranklinChen commented 6 years ago

This replaces https://github.com/rust-lang/rust/issues/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 https://github.com/rust-lang/rust/pull/49255

est31 commented 6 years ago

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 commented 5 years ago

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() {
  |                            ^^^^^^^^^