generics - E0308 具有简单泛型函数的不匹配类型

标签 generics rust

<分区>

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

但是编译失败并提示信息

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 (082e47636 2015-08-03)

最佳答案

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
}

关于generics - E0308 具有简单泛型函数的不匹配类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32437664/

相关文章:

generics - 通用序列

swift - 为什么struct在转换为字典时需要符合Hashable以及Generic数组

c# - 为什么这段代码会提示 "the arity of the generic type definition"?

java - 如果重写方法没有,为什么重写方法不能指定类型参数?

function - 为什么函数指针的行为在 Rust 中会根据函数指针的可变性而有所不同?

rust - 你如何将 Vec 的切片发送到 Rust 中的任务?

java - 为什么我不能初始化 Map<int, String>?

rust - 将两个整数相除不会在 Rust 中打印为十进制数

multithreading - Rust:并发错误,程序在第一个线程后挂起

rust - 如何轻松借用 Vec<Vec<T>> 作为 &[&[T]]?