How to use generics (for support integers and floats) in this function?

My raise to power func:

fn pow(number: i32, power: i32) -> i32 {
    let mut curr_num = number;
    let mut curr_pow = power;

    while curr_pow != 1 {
        curr_num *= number;
        curr_pow -= 1;
    }

    curr_num
}

See if you can use num::pow::Pow - Rust instead - it'll likely cover all the cases you're interested in.

If you just want to see what a generic version of your approach would look like, then it can be something like this:

// This is also from the `num` crate
use num::Num;
use std::ops::{MulAssign, SubAssign};

fn pow<T: Num + Copy + MulAssign + SubAssign>(number: T, power: T) -> T {
    let mut curr_num = number;
    let mut curr_pow = power;

    while curr_pow != T::one() {
        curr_num *= number;
        curr_pow -= T::one();
    }

    curr_num
}
2 Likes

Yes, the traits in num exist to make such generic programming easier.

Regarding pow in particular, you might want to read about exponentiation by squaring, which is how it's done in num::pow and the standard i32::pow et al.