Generic function and Copy

Hi there.
This code is OK:

fn main() {
    println!("{}",mlt(5, 6));
}

fn mlt<T:std::ops::Mul<Output = T>>(a:T, b:T)->T{
return a * b
}

this is ko:

fn main() {
    println!("{}",mlt(5));
}

fn mlt<T:std::ops::Mul<Output = T>>(a:T)->T{
return a * a
}

and i need to add the copy trait. Why this different behaviour?
Thx.

In the first function you only use a once, in the second function you use it twice. So you need to be able to get a second copy of the value somehow.

You can also use references instead, though the bound is a bit more complicated

fn main() {
    println!("{}", mlt(&5));
}

fn mlt<'a, T>(a: &'a T) -> T
where
    &'a T: std::ops::Mul<&'a T, Output = T> + 'a,
{
    a * a
}

or if you want to pass a value instead of a reference you can use a Higher Ranked Trait Bound

fn main() {
    println!("{}", mlt(5));
}

fn mlt<T>(a: T) -> T
where
    for<'a> &'a T: std::ops::Mul<&'a T, Output = T> + 'a,
{
    &a * &a
}
1 Like

Ok, my fault, compiler is clear about this
I have not read with the necessary attention

6 | return a * a
| ----^
| | |
| | value used here after move
| a moved due to usage in operator

thx,