Why do I get the error “the type of this value must be known in this context” when parsing a string to a number?

前端 未结 1 1095
北恋
北恋 2021-01-19 18:41

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

相关标签:
1条回答
  • 2021-01-19 18:52

    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;
    
    0 讨论(0)
提交回复
热议问题