[英]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. 我看到它的方式,我们有一个&str
,我们将它解析为f32
并解开它。 Then we convert the f32
to a u32
. 然后我们将f32
转换为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. 看起来有些东西要求我们将操作分成两个块。
The thing is that parse
isn't just defined for f32
. 问题是parse
不只是为f32
定义的。 parse
can define all kind of types (specifically any type that implements FromStr
). parse
可以定义所有类型的类型(特别是任何实现FromStr
类型)。 So how does Rust know that parse
should return f32
and not for some other type? 那么Rust怎么知道parse
应该返回f32
而不是其他类型呢?
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. 在你的第一个例子中,它知道这一点,因为oneStep
被声明为具有类型f32
,因此Rust可以推断它应该使用f32
作为其类型参数调用parse
。 In the second example f32
isn't mentioned anywhere in the code, so Rust couldn't possibly figure it out. 在第二个例子中,代码中的任何地方都没有提到f32
,所以Rust无法弄明白。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.