Pass []string to a function that expects a variadic parameter

前端 未结 1 1048
日久生厌
日久生厌 2020-12-19 20:06

In order to don\'t repeat my self over and over I wanted to create a function that handles running some commands.

func runCommand(name string, arg ...string         


        
相关标签:
1条回答
  • 2020-12-19 20:30

    You expand the []string with another ...

    cmd := exec.Command(name, arg...)
    

    From the language spec on Passing arguments to ... parameters

    If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.

    Given the slice s and call

    s := []string{"James", "Jasmine"}
    Greeting("goodbye:", s...)
    

    within Greeting, who will have the same value as s with the same underlying array.

    0 讨论(0)
提交回复
热议问题