+运算符的强制输出与函数中的输入相同?

时间:2018-02-26 13:55:55

标签: function generics types rust add

我有一个函数test,它计算N类型的两个变量的总和,返回N。如何指定N::Output类型必须为N

use std::ops::Add;

fn test<N: Add>(num_a: N, num_b: N) -> N {
    num_a + num_b
}

fn main() {
    println!("{:?}", test(5, 7));
}

Playground

error[E0308]: mismatched types
 --> src/main.rs:4:5
  |
3 | fn test<N: Add>(num_a: N, num_b: N) -> N {
  |                                        - expected `N` because of return type
4 |     num_a + num_b
  |     ^^^^^^^^^^^^^ expected type parameter, found associated type
  |
  = note: expected type `N`
             found type `<N as std::ops::Add>::Output`

0 个答案:

没有答案