go - 如何将 slice 作为可变参数输入?

标签 go

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

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

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

最佳答案

The Go Programming Language Specification

Passing arguments to ... parameters

If f is variadic with final parameter type ...T, then within the function the argument is equivalent to a parameter of type []T. At 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 therefore the number of arguments bound to the final parameter and may differ for each call site.


Package exec

func Command

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

Command returns the Cmd struct to execute the named program with the given arguments.

The returned Cmd's Args field is constructed from the command name followed by the elements of arg, so arg should not include the command name itself. For example, 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

关于go - 如何将 slice 作为可变参数输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23723955/

相关文章:

go - 如何使用golang从firebase数据库中读取特定记录?

go - 将插件添加到 go 程序

go - 用Go编写的lambda API的设计

go - 运行 golang 调试器时,VSCode 调试不在 VARIABLES 区域显示映射值

golang 无法执行二进制文件 : Exec format error

twitter - 使用 tweet 去 Anaconda twitter 媒体上传

go - 如何使用 context.Context 与 tcp 连接读取

Golang 包导入 - 找不到包

mongodb - 使用存储在数组中的 _id 从 golang 查询 mongodb

go - 卡夫卡中没有匹配的监听器错误的领导经纪人