Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any trait that specifies numeric functionality?

I'd like to use a trait to bound a generic type, like this hypothetical HasSQRT:

fn some_generic_function<T>(input: &T)
where
    T: HasSQRT,
{
    // ...
    input.sqrt()
    // ...
}
like image 598
Hossein Noroozpour Avatar asked May 18 '16 10:05

Hossein Noroozpour


1 Answers

You can use num or num-traits crates and bound your generic function type with num::Float, num::Integer or whatever relevant trait:

use num::Float; // 0.2.1

fn main() {
    let f1: f32 = 2.0;
    let f2: f64 = 3.0;
    let i1: i32 = 3;

    println!("{:?}", sqrt(f1));
    println!("{:?}", sqrt(f2));
    println!("{:?}", sqrt(i1)); // error
}

fn sqrt<T: Float>(input: T) -> T {
    input.sqrt()
}
like image 113
evilone Avatar answered Sep 30 '22 20:09

evilone