How can I pass a slice as a variadic input?

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

    A list of command arguments can be retrieved from the flag package Args() function. You can then pass this to a function using the variadic input style (func(input...))

    From the Spec:

    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.

    Example:

    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
    }
    

    See The Go spec for more details.

    Playground

提交回复
热议问题