2015-09-07 76 views
0

我是Rust新手,我試圖編寫自己的簡單通用函數。E0308與簡單通用函數不匹配的類型

fn templ_sum<T>(x : T, y : T) -> T 
    where T : std::ops::Add 
{ 
    let res : T = x + y; 
    res 
} 

fn main() 
{ 
    let x : f32 = 1.0; 
    let y : f32 = 2.0; 
    let z = templ_sum(x, y); 
    println!("{}", z); 
} 

但在編譯失敗,消息

error: mismatched types: expected T , found <T as core::ops::Add>::Output (expected type parameter, found associated type) [E0308] main.rs:12 let res : T = x + y;

我很困惑一點。任何人都可以向我解釋我做錯了什麼?

rustc --version:rustc 1.2.0(2015年8月3日082e47636)

回答

5

Add性狀定義了一個名爲Output類型,這是添加的結果類型。該類型是x + y的結果,而不是T

fn templ_sum<T>(x : T, y : T) -> T::Output 
    where T : std::ops::Add 
{ 
    let res : T::Output = x + y; 
    res 
}