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
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 isFloat
which represents a floating-point number.Float
trait provides a lot of methods which are specific to floating-point numbers, but it also extendsNum
andNumCast
traits which allow one to perform numeric operations and obtain generic types from arbitrary primitive numbers. WithFloat
your code could look like this:NumCast::from()
returnsOption
because not all numeric casts make sense, but in this particular case it is guaranteed to work, hence I usedunwrap()
.