How can I pass a slice as a variadic input?

后端 未结 3 857
礼貌的吻别
礼貌的吻别 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:14

    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")


    For example,

    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))
    }
    

    Output:

    hello world
    

提交回复
热议问题