Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

rust

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 and I think this situation is the simplest so far.

I have the following code:

let one_step: f32 = "4.0".parse().unwrap();
let extra_step: u32 = one_step as u32;

println!("{:?}", extra_step);

The way I see it, we have a &str, we parse it to a f32 and unwrap it. Then we convert the f32 to a u32.

Why can't I just do this? Isn't this, practically, the same thing?

let single_step: u32 = "4.0".parse().unwrap() as u32;

println!("{:?}", single_step);

If I try to run this code, I get this error:

error[E0619]: the type of this value must be known in this context
 --> src/main.rs:6:27
  |
6 |     let single_step: u32 = "4.0".parse().unwrap() as u32;
  |                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

It looks like something requires us to break the operation into two chunks.

like image 584
Omar Abid Avatar asked Jan 28 '23 08:01

Omar Abid


1 Answers

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;
like image 145
sepp2k Avatar answered Feb 03 '23 14:02

sepp2k