我想使用一个特征来绑定(bind)一个泛型类型,就像这个假设的 HasSQRT
:
fn some_generic_function<T>(input: &T)
where
T: HasSQRT,
{
// ...
input.sqrt()
// ...
}
最佳答案
您可以使用num或 num-traits用 num::Float
绑定(bind)你的泛型函数类型, num::Integer
或任何相关特征:
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()
}
关于rust - 是否有任何特征可以指定数字功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63854409/