Trait for numerical functionality in Rust

Is there any sign that indicates some numerical functions? I would like to use it to restrict a general type, such as a hypothetical one HasSQRT:

fn some_generic_function<T>(input: &T)
    where T: HasSQRT
{
    // ...
    input.sqrt()
    // ... 
}
+4
source share
1 answer

You can use num or num-traits and associate your generic function type with num::Float, num::Integeror any other attribute:

extern crate num;

use num::Float;

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()
}
+4
source

All Articles