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

2018 Edition: Chapter 19: Returning Closures suggest Box and not impl trait #1514

Closed
jeanphilippeD opened this issue Sep 2, 2018 · 1 comment · Fixed by #4152
Closed

Comments

@jeanphilippeD
Copy link

Hello,
I searched the issues but did not find an existing relevant one.

The only provided solution for returning closure in this section is using Box:
https://doc.rust-lang.org/book/2018-edition/ch19-05-advanced-functions-and-closures.html#returning-closures

fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
    Box::new(|x| x + 1)
}

This now compiles on Rust stable, so it seem like it would be a good alternative to put for this advance topic section:
https://play.rust-lang.org/?gist=ce094b09ea045b0e40a69d3fc3158500&version=stable&mode=debug&edition=2015

fn returns_closure() -> impl Fn(i32) -> i32 {
    |x| x + 1
}

fn main() {
    let c = returns_closure();
    println!("{}", c(5));
}

Thanks,
Jean-Philippe.

@andrerfcsantos
Copy link

I absolutely agree with this.

As a newcomer to Rust I was extremely confused for a while with this, because the book taught me to use Box<dyn Trait> but I saw everyone doing the impl Trait syntax. I was confused at first because I didn't even realize both syntaxes were trying to do the same thing and I kinda assumed the impl syntax was a different feature of the language I didn't know about.

Only when googling specifically for this syntax I found the relevant part of the editions guide and realize they are almost the same thing.

I think a simple inclusion in the book about this would be great, since a lot of places are using the impl Trait syntax already.

@carols10cents carols10cents added this to the ch19 milestone Jul 16, 2021
chriskrycho added a commit that referenced this issue Dec 10, 2024
The existing text here has a long historical record; it predates `impl`
or `dyn` existing at all, much less the version we landed on in Rust
2018. Update it to suggest defaulting to `impl Fn`, with trait objects
`Box<dyn Fn>` the fallback.

Fixes #1514
Fixes #3272
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
5 participants