cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
503 stars 82 forks source link

Problems in section 19.4, subsection: Returning closures #168

Closed Tomer-Eliahu closed 3 months ago

Tomer-Eliahu commented 3 months ago

I think there are 3 issues with this specific subsection:

  1. The complier error is out of date. The new complier error is better as it better reflects what I understand to be "best practices" (see issue 2).

  2. Add a note that is better to return an impl Trait instead of a (boxed or otherwise referenced) dyn Trait if possible (i.e. when all returned values are the same type). This is better as it avoids the run-time performance penalties of using a trait object. From the reference.

  3. The line:

you’re not allowed to use the function pointer fn as a return type, for example.

Is flat out incorrect. The following code does compile:

        fn add_one(x: i32) -> i32 {
        x + 1
        }

        //function pointer as return type is actually fine!
        fn return_func(specify: i32) -> fn(i32) -> i32
        {
            match specify{
                1 => add_one,
                _ => panic!("PANIC")

            }
        }

        fn main() {
            let a = return_func(1);
            println!("add_one(1) is {}", a(1));//prints add_one(1) is 2
        }

In fact, in some cases you can coerce closures to function pointers:

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

fn main() {
    let a = returns_closure();
    println!("add_one(1) is {}", a(1));//prints add_one(1) is 2
}
willcrichton commented 3 months ago

I will fix the wording about the return type. (The error messages all get updated when we bump the Rust version for the whole book.)