英文:
Pass []string to a function that expects a variadic parameter
问题
为了避免重复编写代码,我想创建一个处理运行某些命令的函数。
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函数?
英文:
In order to don't repeat my self over and over I wanted to create a function that handles running some commands.
func runCommand(name string, arg ...string) error {
cmd := exec.Command(name, arg)
if err := cmd.Run(); err != nil {
return err
} else {
return nil
}
}
Once I try to run this I get the following error:
cannot use arg (type []string) as type string in argument to exec.Command
I had a look into the implementation of the os.Command and it looks that the function signature is exact what I supply.
Internally a []string should be the same as variadic parameter but for the compiler it seems not.
Is there a way to pass the variadic parameter into the Command?
答案1
得分: 20
你可以使用...将[]string扩展为另一个参数。
cmd := exec.Command(name, arg...)
根据语言规范中关于传递参数给...参数的说明:
如果最后一个参数可以赋值给切片类型
[]T,并且在参数后面跟着...,则可以将其不变地作为...T参数的值传递。在这种情况下,不会创建新的切片。给定切片
s和调用s := []string{"James", "Jasmine"} Greeting("goodbye:", s...)在
Greeting函数内部,who将具有与s相同的值和相同的底层数组。
英文:
You expand the []string with another ...
cmd := exec.Command(name, arg...)
From the language spec on Passing arguments to ... parameters
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论