0

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 Integers, 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?

Kotte
  • 811
  • 1
  • 9
  • 21
  • I believe your question is answered by the answers of [generic type without a lifetime parameter](https://stackoverflow.com/q/47996700/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster May 23 '18 at 21:08
  • 1
    [This answer](https://stackoverflow.com/a/47997981/3131852) to the linked question applies here as well. – Tim Diekmann May 23 '18 at 21:38
  • Ah, thank you. That gave me exactly what I needed :-). – Kotte May 24 '18 at 05:33

0 Answers0