2015-09-07 75 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 
}