如何使Rust函数接受任何浮动类型作为参数 [英] How can I make a Rust function accept any floating type as an argument
问题描述
我正在寻找一个可以接受任何浮点数据的函数,类似于以下形式:
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中具有原始数值类型的通用故事都可以在官方 Float
,它代表一个浮点数.
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
特质提供了许多特定于浮点数的方法,但它也扩展了 NumCast
特性,允许人们执行数字运算并从任意原始数字中获取泛型.使用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屋!