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 ;
pub fn test3() { let example_closure = |x| x; let s = example_closure(String::from("hello")); let n = example_closure(5); }
--> src/base/k_closure.rs:53:29 | 53 | let n = example_closure(5); | ^ | | | expected struct `String`, found integer | help: try using a conversion method: `5.to_string()`
The first time we call example_closure
with the String
value, the compiler infers the type of x
and the return type of the closure to be String
. Those types are then locked into the closure in example_closure
, and we get a type error if we try to use a different type with the same closure.
不换数据类型,下面的是正确的
pub fn test3() { let example_closure = |x| x; let s = example_closure(6); println!("{}",s); let n = example_closure(5); println!("{}",n); }
6 5