Trait for numeric functionality in Rust

試著忘記壹切 提交于 2019-12-17 07:52:14

问题


Is there any trait that specifies some numeric functionality? I'd like to use it for bounding a generic type, like this hypothetical HasSQRT:

fn some_generic_function<T>(input: &T)
    where T: HasSQRT
{
    // ...
    input.sqrt()
    // ... 
}

回答1:


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

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()
}


来源:https://stackoverflow.com/questions/37296351/trait-for-numeric-functionality-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!