Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ch19-05: Enhance Returning Closures section #2725

Conversation

mgacek8
Copy link

@mgacek8 mgacek8 commented May 16, 2021

This PR enhances Returning Closures section from ch19-05.
It mentions the impl Trait syntax for returning closures from functions, as another way except Trait objects.
Previously suggestion to use that was in the compiler error, but the Book depicted only Trait objects as a solution.
Now, two ways of returning a closure from a function are present.

fixes: #1514

Welcome any feedback! (this is my first PR to the Book)

Mentioned `impl Trait` syntax for returning closures from functions,
as another way except Trait objects.
@carols10cents carols10cents added this to the ch19 milestone Jul 22, 2021
@conradludgate
Copy link

I just came to propose this suggestion too. The error log suggests using impl too

$ cargo build
   Compiling functions-example v0.1.0 (file:///projects/functions-example)
error[E0746]: return type cannot have an unboxed trait object
 --> src/lib.rs:1:25
  |
1 | fn returns_closure() -> dyn Fn(i32) -> i32 {
  |                         ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = note: for information on `impl Trait`, see <https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits>
help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:14]`, which implements `Fn(i32) -> i32`
  |
1 | fn returns_closure() -> impl Fn(i32) -> i32 {
  |                         ^^^^^^^^^^^^^^^^^^^

@chriskrycho
Copy link
Contributor

Thanks for this! I went ahead and did a bit more of a rewrite just now, to tackle the same issue as well as a related one, in #4152, but this PR was nonetheless appreciated!

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

Successfully merging this pull request may close these issues.

2018 Edition: Chapter 19: Returning Closures suggest Box and not impl trait
4 participants