我是Rust的新手,我正在尝试编写自己的简单泛型函数.
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);
}
Run Code Online (Sandbox Code Playgroud)
但编译失败的消息
错误:不匹配的类型:expected
T,found<T as core::ops::Add>::Output(期望的类型参数,找到的关联类型)[E0308] main.rs:12让res:T = x + y;
我有点困惑.谁能向我解释我做错了什么?
rustc --version:rustc 1.2.0(082e47636 2015-08-03)
所述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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
374 次 |
| 最近记录: |