試圖編譯如下,爲什麼這種類型不允許使用類型參數?
fn do_it() -> Result<i32, u32> {
Result::<i32, u32>::Ok(3)
}
fn main() {
println!("{}", do_it());
}
結果:
./result_test.rs:2:14: 2:17 error: type parameters are not allowed on this type [E0109]
./result_test.rs:2 Result::<i32, u32>::Ok(3)
^~~
爲什麼類型參數不允許這種類型的?
這是一個最小的例子,我的現實世界的例子是試圖返回下面的宏:
match $reader.$read_func() {
Ok(n) => Result::<$read_type, LocalReadError>::Ok(n),
Err(err) => Result::<$read_type, LocalReadError>::Err(
LocalReadError::from(err)
),
}
$read_func
是一個函數,$read_type
是函數的返回類型。 (如果我有一個程序化的方式來獲取它,我會這麼做;我不知道如何,所以它是一個arg ...);原樣,我得到了上述錯誤。如果我刪除了泛型參數的規範,請鍵入inteference抱怨它無法確定類型。 (?因爲它在match
的一個分支,而在其他Result<$read_type, _>
結束了Result<_, LocalReadError>
我真的不知道它說:
error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [E0282]
match $reader.$read_func() {
^~~~~~~~~~~~
)
注:爲什麼的問題類型參數不允許在下面回答。原來,這不是「無法推斷出足夠的類型信息」的原因。 (read_func
是一個函數,在我的情況下,我傳遞了一個模板化函數,但忘記了模板arg,這是無法推斷出來的。)
這看起來很像一個bug。 https://doc.rust-lang.org/nightly/error-index.html#E0109顯示了它應該做的事情。 –
作爲解決您的實際問題的方法我建議將您的宏更改爲'$ reader。$ read_func()。map_err(LocalReadError :: from)' –
不確定它是否爲錯誤或者實際上是否會出現這種錯誤,作品似乎是:'Result :: Ok ::(3)'。 [嬰兒圍欄(http://is.gd/xNUV9B) –