如何使Rust函数接受任何浮动类型作为参数 [英] How can I make a Rust function accept any floating type as an argument

查看:241
本文介绍了如何使Rust函数接受任何浮动类型作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可以接受任何浮点数据的函数,类似于以下形式:

I'm looking to write a function that can accept any floating point data, similar to the following form:

fn multiply<F: Float>(floating_point_number: F) -> F {
    floating_point_number * 2
}

但是我在文档中找不到语法,也找不到仅浮点数共有的特征.

But I can't find the syntax for it in the documentation, or a trait that is common to floating point numbers only.

推荐答案

当前,所有在Rust中具有原始数值类型的通用故事都可以在官方

Currently all of the generic story with primitive numeric types in Rust is available in the official num crate. This crate contains, among everything else, a number of traits which are implemented for various primitive numeric types, and in particular there is Float which represents a floating-point number.

Float特质提供了许多特定于浮点数的方法,但它也扩展了

Float trait provides a lot of methods which are specific to floating-point numbers, but it also extends Num and NumCast traits which allow one to perform numeric operations and obtain generic types from arbitrary primitive numbers. With Float your code could look like this:

use num::{Float, NumCast};

fn multiply<F: Float>(n: F) -> F {
    n * NumCast::from(2).unwrap()
}

NumCast::from()返回Option,因为并非所有数字强制转换都有意义,但是在这种情况下,可以保证可以正常工作,因此我使用了unwrap().

NumCast::from() returns Option because not all numeric casts make sense, but in this particular case it is guaranteed to work, hence I used unwrap().

这篇关于如何使Rust函数接受任何浮动类型作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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