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

I am not trying to write complex code, I just want to understand what is here (or not). I checked other questions, but they all had difficult 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);

As I see it, we have it &str, we parse it with f32and deploy it. Then we convert f32to u32.

Why can't I do this? Isn't that practically the same?

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;
  |                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Something seems to require us to split the operation into two pieces.

+4
source share
1 answer

, parse f32. parse ( , , FromStr). , Rust , parse f32, - ?

, oneStep f32, Rust , parse f32 . f32 , Rust .

, , . , :

let singleStep: u32 = "4.0".parse::<f32>().unwrap() as u32;
+8

Source: https://habr.com/ru/post/1695774/


All Articles