Variadic Functions in Rust

Here is the translated code example in Rust along with explanation:

Variadic functions can be called with any number of trailing arguments. For example, println! is a common variadic macro in Rust.

Here’s a function that will take an arbitrary number of i32s as arguments.

fn sum(nums: &[i32]) {
    println!("{:?}", nums);
    let mut total = 0;
    for &num in nums {
        total += num;
    }
    println!("{}", total);
}

Within the function, the type of nums is equivalent to &[i32]. We can call nums.len(), iterate over it with a loop, etc.

Variadic functions can be called in the usual way with individual arguments.

fn main() {
    sum(&[1, 2]);
    sum(&[1, 2, 3]);
    
    let nums = vec![1, 2, 3, 4];
    sum(&nums);
}

If you already have multiple args in a vector, pass a reference to the slice using &vec like this.

To run the program, compile and execute it using cargo or rustc.

$ cargo run
# or if you are using rustc
$ rustc variadic-functions.rs
$ ./variadic-functions

The output of running the program will be:

[1, 2]
3
[1, 2, 3]
6
[1, 2, 3, 4]
10

Another key aspect of Rust’s functions is their ability to form closures, which we’ll look at next.