Variadic functions in Go
The last parameter can take any number of arguments, arriving as a slice.
func total(label string, values ...int) string {
sum := 0
for _, value := range values {
sum += value
}
return fmt.Sprintf("%s=%d over %d values", label, sum, len(values))
}
func callers() []string {
scores := []int{3, 2, 1}
return []string{
total("inline", 1, 2, 3),
total("spread", scores...),
total("empty"),
}
}
How it works
- Inside the function it is an ordinary slice.
slice...spreads an existing slice into the call.- Passing none gives a nil slice, which ranges fine.
Keywords and builtins used here
forfuncintlenrangereturnstring
The run, in numbers
- Lines
- 16
- Characters to type
- 316
- Tokens
- 95
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 63 seconds.
Step 2 of 6 in Functions, step 11 of 30 in Language basics.