book icon indicating copy to clipboard operation
book copied to clipboard

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

Open jeanphilippeD opened this issue 6 years ago • 1 comments

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.

jeanphilippeD avatar Sep 02 '18 19:09 jeanphilippeD

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.

andrerfcsantos avatar Mar 28 '21 10:03 andrerfcsantos