[Golang] Pass Slice or Array to Variadic Function
What is ... in Go Function Parameter? [2]
dot dot dot (...) in final parameter of Go function means you can pass zero, one, or more arguments for that parameter according to Function types in Go spec, and the function of such kind is usually called variadic function.
For example, assume we have the following function:
func giveMeString(s ...string)
We can invoke the function by:
giveMeString()
giveMeString("hello")
giveMeString("hello", "world")
The function can be invoked with more string arguments as you like. You can run above example in Go Playground to fiddle the code by yourself.
One more well-known example is fmt.Println in Go Standard library. You can also try it in Go Playground.
Pass Slice or Array as Variadic Parameter [1]
Continue the above example. Assune we have a slice of []string as follows:
myStrSlice := []string{"hello", "world"}
How to pass the slice to the following function?
func giveMeString(s ...string)
Answer: append ... after the name of the slice.
giveMeString(myStrSlice...)
The same if we have the following array:
myStrArray := [2]string{"hello", "world"}
Pass it to the above variadic function via:
giveMeString(myStrArray[:]...)
You can try to pass slice or array of above example on Go Playground.
Tested on: The Go Playground
References:
[1] |
[2] |
[3] | Go Slices: usage and internals - The Go Blog |
[4] | [Golang] Variadic Function Example - addEventListener |
[5] | Go語言 函數參數點點點(...)意義 |
[6] | The Go variadic function, comparing errors in Golang, solving triangles & more : golang |
[7] | Standard Library Variadic Functions accepting an arbitrary number of arbitrary objects : golang |