rust-lang / mdBook

Create book from markdown files. Like Gitbook but implemented in Rust
https://rust-lang.github.io/mdBook/
Mozilla Public License 2.0
18.37k stars 1.65k forks source link

Example with closure in chapter 13-01 (code listing without num but between 13-2 and 13-3 #2356

Closed OlegBash599 closed 7 months ago

OlegBash599 commented 7 months ago

Question

There is an example with closure here ( https://doc.rust-lang.org/book/ch13-01-closures.html ) in code listing without number-reference but between code listing 13-2 and 13-3. They say:

This illustrates how closure syntax is similar to function syntax except for the use of pipes and the amount of syntax that is optional:

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 ;

but i have tried to compile the following (without type annotation as in example):

fn closure_inside_like_add_one_fn(){ let add_ove_v2 = |x: u32| -> u32 { x + 1 }; let add_one_v3 = |x| { x + 1 }; let add_one_v4 = |x| x + 1 ; }

and get message from compiler:

help: consider giving this closure parameter an explicit type let add_one_v3 = |x: / Type /| { x + 1 };

What is wrong? Compiler require type, but no type in book sample. Please explain/clarify (I am new to Rust) or correct the chapter :-)

Should be the following closure definition more correct? at least it is compiling...

fn closure_inside_like_add_one_fn(){ let add_ove_v2 = |x: u32| -> u32 { x + 1 }; let add_one_v3 = |x: u32| { x + 1 }; let add_one_v4 = |x: u32| x + 1 ; }

Version

No response

ehuss commented 7 months ago

The reason is described in the paragraph just below the example:

The add_one_v3 and add_one_v4 lines require the closures to be evaluated to be able to compile because the types will be inferred from their usage.

That means you need to include code that will call the closure for the type inference system to determine the type of the x parameter.

This issue tracker is for the mdbook tool, and is not for the Rust book. In the future, please try asking your question on one of the user forums, such as https://users.rust-lang.org/, or if there is feedback that something in the Rust book isn't clear, please head over to their issue tracker at https://github.com/rust-lang/book/issues.

OlegBash599 commented 7 months ago

Thank you very much for the explanation and links specified!