How can I make the Rust function accept any floating-point type as an argument

I want 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 cannot find the syntax for it in the documentation or the trait that is common only to floating point numbers

+7
generics polymorphism rust
source share
1 answer

Currently, the whole common history with primitive numeric types in Rust is available in the official num container. Among other things, this box contains a number of features that are implemented for various primitive numeric types, and in particular there is a Float , which represents a floating-point number.

Float shows many methods specific to floating point numbers, but num and NumCast are also distributed, which allow you to perform numerical operations and get common types from arbitrary primitive numbers. With Float your code might 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 clicks make sense, but in this particular case it is guaranteed to work, so I used unwrap() .

+11
source share

All Articles