Variadic functions
- Version
- 1.27
- Review
- Draft
Summary#
A final parameter written ...T accepts zero or more arguments. Inside the function it is a []T. Add ... after a slice argument to pass that slice itself.
Syntax#
func join(separator string, parts ...string) string
join("/", "usr", "local")
join("/", segments...)
Example#
package main
import (
"fmt"
"strings"
)
func route(host string, segments ...string) string {
fmt.Println("segments:", len(segments), "nil:", segments == nil)
return host + "/" + strings.Join(segments, "/")
}
func maskFirst(words ...string) {
if len(words) > 0 {
words[0] = "***"
}
}
func main() {
fmt.Println(route("example.test"))
fmt.Println(route("example.test", "users", "7"))
path := []string{"teams", "core"}
fmt.Println(route("example.test", path...))
maskFirst(path...) // the function gets this slice
fmt.Println(path)
}
Expected output#
segments: 0 nil: true
example.test/
segments: 2 nil: false
example.test/users/7
segments: 2 nil: false
example.test/teams/core
[*** core]
Common mistakes#
Passing values... shares the slice's backing array, so changes to its elements are visible to the caller. Copy the slice first to keep its elements unchanged. For the variadic parameter, pass either individual arguments or one slice with .... To pass a []string to a ...interface{} parameter, copy the elements into a []interface{} first.
Version applicability#
The syntax and example work from Go 1.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0