Title here
Summary here
Here’s a function that will take an arbitrary number of int
s as arguments.
fn sum(nums: &[i32]) {
println!("{:?} ", nums);
let mut total = 0;
for &num in nums {
total += num;
}
println!("{}", total);
}
fn main() {
// Variadic functions can be called in the usual way with individual arguments.
sum(&[1, 2]);
sum(&[1, 2, 3]);
// If you already have multiple args in a slice, apply them to a variadic function using ...
let nums = vec![1, 2, 3, 4];
sum(&nums);
}
To compile and run the Rust program, use the following commands:
$ rustc main.rs
$ ./main
[1, 2] 3
[1, 2, 3] 6
[1, 2, 3, 4] 10