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.
The above code show how to define a function variable in rust. First we define a function named add. In this function, we specify the return type explicitly. Unlike scala, in rust return types are not type inferred. The last line of the function is considered as return statement.
As a refresher, when we want to pass functions around in Rust, we normally resort to using the function traits Fn, FnMut and FnOnce. The function type fn (foo) -> bar can also be used but is decidedly less powerful.
On the way, I'll look at trait families, and a way to avoid overlapping impls. As a refresher, when we want to pass functions around in Rust, we normally resort to using the function traits Fn, FnMut and FnOnce. The function type fn (foo) -> bar can also be used but is decidedly less powerful.
Anonymous functions are in rust are part of closure feature of rust. Closures are special functions which has access to their surrounding scope. So anonymous functions are closures with empty scope. The above code show how to pass an anonymous function. You can read more about rust closures here.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With