Closed OlegBash599 closed 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.
Thank you very much for the explanation and links specified!
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:
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:
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