如何创建具有可变数量参数的函数? [英] How can I create a function with a variable number of arguments?

查看:39
本文介绍了如何创建具有可变数量参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

喜欢这个Java代码:

Like this Java code:

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

推荐答案

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

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"]);
}

(游乐场)

除此之外,您还可以明确接受可选参数:

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);
}

(游乐场)

如果你需要接受许多参数,无论是否可选,你可以实现一个构建器:

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"));
}

(游乐场)

这篇关于如何创建具有可变数量参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆