是否有任何指定数字功能的特征? [英] Is there any trait that specifies numeric functionality?

查看:19
本文介绍了是否有任何指定数字功能的特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 trait 来绑定泛型类型,就像这个假设的 HasSQRT:

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

推荐答案

您可以使用 numnum-traits crates 并用 num::Float, num::Integer 或任何相关特征:

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

这篇关于是否有任何指定数字功能的特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆