How can I pass a slice as a variadic input?

后端 未结 3 869
礼貌的吻别
礼貌的吻别 2020-11-27 04:24

I have a function func more(... t). I\'m wondering if it\'s possible to use a slice to populate a list of arguments ... .

I\'m trying to s

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 05:23

    func Command

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

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

    So you have to extract the command which is found at sliceA[0] and then pass all the arguments with a variadic but removing the command sliceA[1:]....

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

提交回复
热议问题