将 []string 传递给一个期望可变参数的函数

5
为了避免重复,我想创建一个处理运行某些命令的函数。
func runCommand(name string, arg ...string) error {
    cmd := exec.Command(name, arg)
    if err := cmd.Run(); err != nil {
        return err
    } else {
        return nil
    }
}

当我尝试运行这个程序时,出现以下错误:

cannot use arg (type []string) as type string in argument to exec.Command

我查看了os.Command的实现情况,发现函数签名与我提供的完全相同。
内部上,[]string应该与可变参数相同,但对于编译器似乎不是这样。
是否有方法将可变参数传递到Command中?
1个回答

20
您可以使用另一个...扩展[]string
cmd := exec.Command(name, arg...)

来自语言规范参数传递部分:

If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.

Given the slice s and call

s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)

within Greeting, who will have the same value as s with the same underlying array.


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接