我有一個關於泛型在Rust(1.0版)的新手問題。鑄造到一個通用的類型
假設我寫了一個通用函數來進行除法。沒關係這種功能的用處;讓這個問題簡單化是一個簡單的功能。
fn divide<T: std::ops::Div>(a: T, b: T) -> T {
a/b
}
fn main() {
println!("{}", divide(42, 18))
}
該程序未能編譯。
src/main.rs:2:5: 2:10 error: mismatched types:
expected `T`,
found `<T as core::ops::Div>::Output`
(expected type parameter,
found associated type) [E0308]
src/main.rs:2 a/b
^~~~~
我明白,編譯器錯誤是告訴我,除法運算的結果是一個類型Output
,不T
,我看到standard library documentation的Output
類型。
如何將Output
轉換爲T
?我嘗試使用as
進行施放。
fn divide<T: std::ops::Div>(a: T, b: T) -> T {
(a/b) as T
}
fn main() {
println!("{}", divide(42, 18))
}
這會導致不同的編譯器錯誤。
src/main.rs:2:5: 2:17 error: non-scalar cast: `<T as core::ops::Div>::Output` as `T`
src/main.rs:2 (a/b) as T
^~~~~~~~~~~~
我的想法,使這項工作,我意識到我缺乏的關於語言的東西基本瞭解這裏,但我甚至不知道要尋找什麼,使這項工作。幫幫我?
可能是http://stackoverflow.com/q/29184358/155423的副本。 – Shepmaster