0

I'm trying to write some numerically templated functions and I'm finding a number of stumbling blocks. One I recently found is the following code:

extern crate num;
use num::Integer;
use num::Zero;

fn f<T: Integer>() -> T {
    T::zero() + 1
}

fn main() {
    let x: u32 = f();
    println!("{}", x);
}

This doesn't work, because 1 is a "mismatched type" and the compiler "expected type parameter, found integral variable".

Now, I know that T::zero() + T::one() does work and "fixes" the above problem, but what if I use numeric literals for which there is nothing like Zero, like 2, 10, 100?

1 Answers1

1

FromPrimitive or Num::from_str_radix seems to match your need.

extern crate num;
use num::{Integer, FromPrimitive};

fn f<T: Integer + FromPrimitive>() -> T {
    T::zero() + T::from_i32(1).unwrap()
}

fn main() {
    let x: u32 = f();
    println!("{}", x);
}

or

extern crate num;
use num::Integer;

fn f<T: Integer>() -> T {
    T::zero() + T::from_str_radix("1", 10).ok().unwrap()
}

fn main() {
    let x: u32 = f();
    println!("{}", x);
}
Masaki Hara
  • 3,295
  • 21
  • 21