How can I make a Rust function accept any floating

2019-02-21 14:35发布

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){
    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

1条回答
爷、活的狠高调
2楼-- · 2019-02-21 15:06

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 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() returns Option because not all numeric casts make sense, but in this particular case it is guaranteed to work, hence I used unwrap().

查看更多
登录 后发表回答