1

I'm new to Rust and I'm trying to write my own simple generic function.

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

But compiling failed with message

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;

I am confused a little. Can anyone explain to me what I'm doing wrong?

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

sellibitze
  • 27,611
  • 3
  • 75
  • 95
Daiver
  • 1,488
  • 3
  • 18
  • 47

1 Answers1

6

The Add trait define a type called Output, which is the result type of the addition. That type is the result of x + y, not T.

fn templ_sum<T>(x : T, y : T) -> T::Output
    where T : std::ops::Add
{
    let res : T::Output = x + y;
    res
}
eulerdisk
  • 4,299
  • 1
  • 22
  • 21