Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...