Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 848
timlyo Avatar asked Mar 15 '16 14:03

timlyo


People also ask

How to define a function variable in rust?

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.

How do you pass a function around in rust?

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.

How to avoid overlapping impls in rust?

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.

What is an anonymous function in rust?

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.


Video Answer


1 Answers

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().

like image 129
Vladimir Matveev Avatar answered Sep 26 '22 02:09

Vladimir Matveev