如何将一个切片作为可变输入传递?

我有一个函数 func more(... t)。我想知道是否可以使用一个切片来填充参数 ...的列表。

我正在尝试解决下面的程序。基本上是模拟一个普通的 shell,它以字符串的形式接收命令。 命令 函数需要一个参数“列表”,我不知道如何将字符串转换成这样的列表

    import "os/exec"
import "strings"
func main(){
plainCommand  := "echo hello world"
sliceA := strings.Fields(plainCommand)
cmd := exec.Command(sliceA)
}
64694 次浏览

可以从 标志包 Args()函数中检索命令参数列表。然后您可以使用可变输入样式(func(input...))将其传递给函数

来自 规格:

如果 f 是最终参数类型为... T 的可变参数,那么在函数内部,参数等价于类型为[] T 的参数。在每次调用 f 时,传递给最终参数的参数是类型为[] T 的一个新片段,其后续元素是实际参数,所有参数都必须赋值给类型为 T 的参数。

例如:

package main


import "fmt"


func echo(strings ...string) {
for _, s := range strings {
fmt.Println(s)
}
}


func main() {
strings := []string{"a", "b", "c"}
echo(strings...) // Treat input to function as variadic
}

有关详细信息,请参阅 Go 规范

游乐场

围棋编程语言规范

将参数传递给... 参数

如果 f 是可变的,最终参数类型为... T,则在 参数等效于[] T 类型的参数 each call of f, the argument passed to the final parameter is a new slice of type []T whose successive elements are the actual arguments, which all must be assignable to the type T. The length of the slice is 因此,绑定到最终参数的参数的数目可能 每个呼叫站点不同。


包裹执行

命令

func Command(name string, arg ...string) *Cmd

命令返回 Cmd 结构来执行命名的程序 给予争论。

返回的 Cmd 的 Args 字段由命令名构造 后面跟着 arg 的元素,所以 arg 不应该包含命令 例如,Command (“ echo”,“ hello”)


比如说,

package main


import (
"fmt"
"os/exec"
)


func main() {
name := "echo"
args := []string{"hello", "world"}
cmd := exec.Command(name, args...)
out, err := cmd.Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}

产出:

hello world

命令

func Command(name string, arg ...string) *Cmd

命令返回 Cmd 结构来执行具有给定参数的命名程序。

因此,您必须提取在 sliceA[0]处找到的命令,然后使用可变参数传递所有参数,但是要删除命令 sliceA[1:]...

import "os/exec"
import "strings"
func main(){
plainCommand  := "echo hello world"
sliceA := strings.Fields(plainCommand)
cmd := exec.Command(sliceA[0], sliceA[1:]...)
}