I\'m not trying to write sophisticated code, I just want to understand what is (or is not) going on here. I checked other questions but they all had complicated situations a
The thing is that parse
isn't just defined for f32
. parse
can define all kind of types (specifically any type that implements FromStr
). So how does Rust know that parse
should return f32
and not for some other type?
In your first example it knows this because oneStep
is declared to have type f32
, so Rust can infer that it should call parse
with f32
as its type argument. In the second example f32
isn't mentioned anywhere in the code, so Rust couldn't possibly figure it out.
Instead of inferring the type argument from the type of a variable, you can also pass it directly. That way it will work in a single step:
let singleStep: u32 = "4.0".parse::<f32>().unwrap() as u32;