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

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年9月22日 23:34:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/32721066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定