How to make function with Generic input type and multiple/optional input parameters

Let's say I've the below function as baseline:

fn sum(a: i32, b: i32) -> i32 {
    a + b
}

and I want to replace it by a function that:

  1. Accept different type of numerical input parameters (i32, f64, ..)
  2. Accept different number of input parameters, 2, 3, 4, ... as the user enter

i.e. how to write a single function to run the following 2 statement:

let x = sum(2, 3.1);
let y = sum(4.2, 6.3, 5.2, 10);

It'll be much easier to make it a macro.

With generics you're going to face these problems:

  • Rust doesn't have variable number of function arguments, so you'll have to use tuples as the input

  • You will have to use traits to describe every operation you want to perform, with exact inputs and outputs. It will be very verbose and difficult to work with. Crates like num-traits might help a bit.

3 Likes

Thanks, I made this one:

macro_rules! sum{
    ($($element:expr), *) => {
        {
            let mut sum = 0f64;
            $(sum += $element as f64;)*
            sum
        }
    };
}

fn main() {
    println!("sum: {}", sum!(1,2.3,3));
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.