如何创建一个参数数量可变的函数?

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

如何在 Rust 中创建参数数量可变的函数?

像这样Java代码:

void foo(String... args) {
    for (String arg : args) {
        System.out.println(arg);
    }
}

一般来说,你不能 - Rust 不支持可变参数函数,除非与使用可变参数的 C 代码进行互操作。

这种情况下,因为你所有的参数都是同一类型,你可以接受一个切片:

fn foo(args: &[&str]) {
    for arg in args {
        println!("{}", arg);
    }
}

fn main() {
    foo(&["hello", "world", "I", "am", "arguments"]);
}

(Playground)

除此之外,您还可以显式接受可选参数:

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)

如果你需要接受很多参数,可选或不可选,你可以实现一个构建器:

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)

fn variable_func<T>(_vargs: &[T]) {}

fn main() {
    variable_func(&[1]);
    variable_func(&[1, 2]);
    variable_func(&["A", "B", "C"]);
}

在您的类型可能不同的一般情况下,您可以使用宏:

macro_rules! print_all {
    ($($args:expr),*) => {{
        $(
            println!("{}", $args);
        )*
    }}
}

fn main() {
    print_all!(1, 2, "Hello");
}

Playground

再举个例子,如果你想折叠参数,你可以这样做:

macro_rules! sum {
    ($($args:expr),*) => {{
        let result = 0;
        $(
            let result = result + $args;
        )*
        result
    }}
}

fn main() {
    assert_eq!(sum!(1, 2, 3), 6);
}

Playground

请参阅 Rust book's simplified implementation of vec![...] 以获取另一个示例。