I'm studying Rust and trying to write Rust code using closure.
I found some confusing error about Type Inference of Rust.
This post is just a memorandum of understanding for mechanism of Rust.
fn main() { // closure // argument x is set without type annotation. let closure = |x| x; // calling closure two times with different type argument. let a = closure(String::from("Hello")); // passing string. let b = closure(5); // passing integer }
Without type annotation in closure script, Rust inferences the type of the argument.
In this case, the first String argument was passed to the closure, Rust inferences the "x" would be a String value.
But in the next line, integer(u32) value was passed, and then Rust thinks that the argument is a wrong type value,
so it occurs an error, mentioned as below.
error[E0308]: mismatched types --> src/main.rs:14:29 | 14 | let n = example_closure(5); | ^ | | | expected struct "std::string::String", found integral variable | help: try using a conversion method: "5.to_string()" | = note: expected type std::string::String found type "{integer}"