I'm almost certain that this has been asked in multiple ways before. But I'm not really sure on what to search for.
I'm trying write a faculty function that operates on Integer
s, and since integers can be BigInts
I would like to try to use references as much as possible. And also of course to better understand how to use lifetimes and references.
The code looks like this
pub fn faculty<T>(mut n: T) -> T
where
T: num::Integer + num::Unsigned + MulAssign<&T> + SubAssign<&T>,
{
let one: T = T::one();
let mut result: T = T::one();
while n > one {
result *= &n;
n -= &one;
}
result
}
However, the compiler tells me that I'm missing lifetime specifiers for MulAssign
and SubAssign
, and it seems a bit off adding lifetime parameters to a function that neither takes a reference nor returns one.
I tried doing something like
pub fn faculty<'a, 'b, 'c, T: 'c>(mut n: T) -> T
where
T: num::Integer + num::Unsigned + MulAssign<&'a T> + SubAssign<&'b T>,
Which gives the error "The parameter type T
may not live long enough".
So, how do write my function correctly, so I can use operations like result *= &n;
in my code?