将[]字符串传递给需要可变参数的函数 [英] 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
}
}
一旦我尝试运行它,我会收到以下错误:
can not在参数中使用arg(type [] string)作为类型字符串给exec.Command
我看了一下执行 os。命令
,它看起来功能签名与我提供的完全一致。
在内部,一个 []字符串
应该与可变参数相同,但是对于编译器来说,它看起来不是。
有没有办法将variadic参数传递给命令
?
... $ c展开 []字符串
cmd:= exec.Command(name,arg ...)
如果最后一个参数可以赋值给一个切片类型 [] T
,它可能是
传递不变作为 ... T
参数的值,如果参数是
后跟 ...
。在这种情况下,不会创建新的切片。
给定切片和调用
s:= [] string {James,Jasmine}
问候(goodbye:,s ...)
在Greeting中, who
与 s
具有相同的底层数组。
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
?
解决方案 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.
这篇关于将[]字符串传递给需要可变参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!