Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a function with a variable number of arguments?

How can I create a function with a variable number of arguments in Rust?

Like this Java code:

void foo(String... args) {     for (String arg : args) {         System.out.println(arg);     } } 
like image 373
Tiago Avatar asked Mar 09 '15 20:03

Tiago


People also ask

How do you write a function with variable number of arguments in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

Which function accepts a variable number of arguments?

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.

How do you make a function take any number of arguments?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.


1 Answers

In general, you can't - Rust does not support variadic functions, except when interoperating with C code that uses varargs.

In this case, since all of your arguments are the same type, you can accept a slice:

fn foo(args: &[&str]) {     for arg in args {         println!("{}", arg);     } }  fn main() {     foo(&["hello", "world", "I", "am", "arguments"]); } 

(Playground)

Beyond that, you can explicitly accept optional arguments:

fn foo(name: &str, age: Option<u8>) {     match age {         Some(age) => println!("{} is {}.", name, age),         None      => println!("Who knows how old {} is?", name),     } }  fn main() {     foo("Sally", Some(27));     foo("Bill", None); } 

(Playground)

If you need to accept many arguments, optional or not, you can implement a builder:

struct Arguments<'a> {     name: &'a str,     age: Option<u8>, }  impl<'a> Arguments<'a> {     fn new(name: &'a str) -> Arguments<'a> {         Arguments {             name: name,             age: None         }     }      fn age(self, age: u8) -> Self {         Arguments {             age: Some(age),             ..self         }     } }  fn foo(arg: Arguments) {     match arg.age {         Some(age) => println!("{} is {}.", arg.name, age),         None      => println!("Who knows how old {} is?", arg.name),     } }  fn main() {     foo(Arguments::new("Sally").age(27));     foo(Arguments::new("Bill")); } 

(Playground)

like image 105
Shepmaster Avatar answered Oct 26 '22 11:10

Shepmaster