【问题标题】:E0308 mismatched types with simple generic function [duplicate]E0308 具有简单泛型函数的不匹配类型 [重复]
【发布时间】:2015-09-07 11:31:40
【问题描述】:

我是 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);
}

但编译失败并显示消息

错误:不匹配的类型:预期 T, 找到&lt;T as core::ops::Add&gt;::Output(预期类型参数, 找到关联类型)[E0308] main.rs:12 let res : T = x + y;

我有点困惑。谁能向我解释我做错了什么?

rustc --version: rustc 1.2.0 (082e47636 2015-08-03)

【问题讨论】:

    标签: generics rust


    【解决方案1】:

    Add trait 定义了一个名为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
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 2011-12-28
      • 2020-10-18
      • 2010-09-20
      相关资源
      最近更新 更多