![](/img/trans.png)
[英]Scala: Why do I get a type mismatch error when I use “Option”?
[英]Why do I get the error “the type of this value must be known in this context” when parsing a string to a number?
我不是想編寫復雜的代碼,我只是想了解這里發生了什么(或不是什么)。 我檢查了其他問題,但他們都有復雜的情況,我認為這種情況到目前為止最簡單。
我有以下代碼:
let one_step: f32 = "4.0".parse().unwrap();
let extra_step: u32 = one_step as u32;
println!("{:?}", extra_step);
我看到它的方式,我們有一個&str
,我們將它解析為f32
並解開它。 然后我們將f32
轉換為u32
。
為什么我不能這樣做? 實際上,這不是一回事嗎?
let single_step: u32 = "4.0".parse().unwrap() as u32;
println!("{:?}", single_step);
如果我嘗試運行此代碼,我會收到此錯誤:
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;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
看起來有些東西要求我們將操作分成兩個塊。
問題是parse
不只是為f32
定義的。 parse
可以定義所有類型的類型(特別是任何實現FromStr
類型)。 那么Rust怎么知道parse
應該返回f32
而不是其他類型呢?
在你的第一個例子中,它知道這一點,因為oneStep
被聲明為具有類型f32
,因此Rust可以推斷它應該使用f32
作為其類型參數調用parse
。 在第二個例子中,代碼中的任何地方都沒有提到f32
,所以Rust無法弄明白。
您可以直接傳遞它,而不是從變量類型推斷類型參數。 這樣它只需一步即可:
let singleStep: u32 = "4.0".parse::<f32>().unwrap() as u32;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.