Chapter 13. Not all anonymous functions are closures
Description of the problem: Chapter 13 makes no difference amongst anonymous functions and closures. An anonymous function is a closure only if it captures some value from its parent scope.
In the examples: fn add_one_v1 (x: u32) -> u32 { x + 1 } let add_one_v2 = |x: u32| -> u32 { x + 1 }; let add_one_v3 = |x| { x + 1 }; let add_one_v4 = |x| x + 1 ;
none of them are closures, they just process the input parameter.
Suggested fix: I believe the whole chapter must be rewritten. If you consider it appropriate I could contribute a corrected version.
If you consider it appropriate I could contribute a corrected version.
No thank you!
@carols10cents I am new to learning Rust, I am learning with the awesome book you wrote with Steve but I have realized that the example above doesn't work.
The rust compiler demands explicit type annotations for the examples, how do I explain that?
fn main() {
fn add_one_v1 (x: u32) -> u32 { x + 1 }
let add_one_v2 = |x: u32| -> u32 { x + 1 };
let add_one_v3 = |x| { x + 1 };
let add_one_v4 = |x| x + 1 ;
}
and this is the error, I ran this on the rust playground
Compiling playground v0.0.1 (/playground)
error[[E0282]](https://doc.rust-lang.org/stable/error_codes/E0282.html): type annotations needed
--> src/main.rs:4:23
|
4 | let add_one_v3 = |x| { x + 1 };
| ^
|
help: consider giving this closure parameter an explicit type
|
4 | let add_one_v3 = |x: /* Type */| { x + 1 };
| ++++++++++++
For more information about this error, try `rustc --explain E0282`.
error: could not compile `playground` (bin "playground") due to previous error
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5f9b1c47dd31b09b97c91279575290f0
@mcasl You definitely can create and use anonymous functions which do not capture their environment in any way, but:
- Right from the start, the book does define closures as “anonymous functions you can save in a variable or pass as arguments to other functions”; this does not rule out non-closure anonymous functions, just says that closures are one kind of anonymous function.
- The rest of the section is focused on closures; notice that the very next subsection is titled “Capturing the Environment with Closures”. That’s because:
- Closures are by far the most common use of anonymous functions in Rust!
Net, the chapter makes perfectly good sense as is, and the distinction is drawn sufficiently for the purposes of learning the language. Hopefully that makes sense!
@rasheedmhd the examples there are not intended to work; they are just showing how the parts of each version of the function definitions line up!