Use a type parameter in `as` expression inside a generic function

Viewed 91

In the code below the type parameter T can only be an integer type.

fn foo<T>() {
    let _ = 0 as T;
}

How to restrict the T to make the function to compile?

1 Answers

You cannot. But you can use a trait for that, e.g. u128: From<T> will accept all integers type. Or you can restrict it to the operations you want to perform on it, e.g. T: std::ops::Add<Output = T>.

You can also use the num-traits crate, that defines a bunch of traits for numeric types and operations. E.g. you can use num_traits::Num trait to accept "anything that is a number", that supports every operation that makes sense. Or PrimInt that additionally supports integer-only operation, such as bitwise operations.

As an example, here's your code with num_traits::Num:

fn foo<T: num_traits::Num>() {
    let _ = T::zero();
}
Related