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 i32
s as arguments.
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.
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
.
The output of running the program will be:
Another key aspect of Rust’s functions is their ability to form closures, which we’ll look at next.