Hos*_*our 7 numeric traits generic-programming rust
是否有任何特征指定一些数字功能?我想用它来绑定泛型类型,就像这个假设HasSQRT:
fn some_generic_function<T>(input: &T)
where T: HasSQRT
{
// ...
input.sqrt()
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用NUM或NUM-性状包装箱及绑定了您的泛型函数类型num::Float,num::Integer或任何相关的特质:
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()
}
Run Code Online (Sandbox Code Playgroud)