如何解析字符串切片并将它们传递给exec.Command函数?

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

How to unpack the slice of string and pass them to exec.Command

问题

我想编写一个函数,将两个字符串切片作为参数传递给一个 shell 命令。我想要做的是解包这两个切片,并将它们传递给 exec.Command

image_tag := "mydocker/mytag"
func buildDockerContainer(dockerArgs []string, otherArgs []string) {
    cmd := exec.Command("docker", "run", "-d", dockerArgs..., image_tag, otherArgs...)
}

然而,在编写这段代码时,Goland 一直给我报语法错误:

Invalid use of '...', the corresponding parameter is non-variadic

我知道可以这样做:

cmdToRun := []string{"run", "-d"}
cmdToRun = append(cmdToRun, append(append(dockerArgs, image_tag), otherArgs...)...)
cmd := exec.Command("docker", cmdToRun...)

但是否有更简洁的方式可以在一行内完成所有这些操作呢?

英文:

I'd like to write a function that puts two slices of strings as arguments in a shell command. What I'm trying to do is to unpack the 2 slices, and pass them to exec.Command.

image_tag := "mydocker/mytag"
func buildDockerContainer(dockerArgs []string, otherArgs []string) {
	cmd := exec.Command("docker", "run", "-d", dockerArgs..., image_tag, otherArgs...)
}

However, when writing this, Goland keeps giving me syntax error:

Invalid use of '...', the corresponding parameter is non-variadic

I know I can do the following:

	cmdToRun := []string{"run", "-d"}
	cmdToRun = append(cmdToRun, append(append(dockerArgs, image_tag), otherArgs...)...)
	cmd := exec.Command("docker", cmdToRun...)

But is there a more elegant way that I can do all these inline?

答案1

得分: 3

使用append函数:

args := append(append(append([]string{"run", "-d"}, dockerArgs...), image_tag), otherArgs...)
cmd := exec.Command("docker", args...)
英文:

Use append:

args:= append(append(append([]string{"run","-d"},dockerArgs...),image_tag),otherArgs...)
cmd := exec.Command("docker", args...)

答案2

得分: 0

exec.Command(name string, arg ...string)在这种情况下与append函数的行为相同。问题在于,如果第一个参数是字符串,后面它只期望字符串,但如果你传递的是切片,那也是可以的。

https://go.dev/play/p/TBi3nsKue5n

当函数期望一个字符串而你传递的是[]string时,不要忘记在切片末尾加上...

英文:

exec.Command(name string, arg ...string) behave same as append function in this case. the problem is that if the first arg is string, later it expect only string, but if you pass instead only slice that is fine.
https://go.dev/play/p/TBi3nsKue5n
and don't forget the ... at the end of a slice, when the function expect a string and you pass []string

huangapple
  • 本文由 发表于 2021年11月5日 04:35:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/69845505.html
匿名

发表评论

匿名网友

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

确定