Variadic functions
- Go course
- Beginner
- Lesson 32/90
- 4 min
Learn to take a variable number of arguments with the ... operator.
Variadic functions
If ... is written before the type of the last parameter, the function takes any number of arguments of that type; inside, they appear as a slice:
func topla(sayilar ...int) int {
t := 0
for _, n := range sayilar {
t += n
}
return t
}
fmt.Println(topla(1, 2, 3)) // 6
fmt.Println(topla()) // 0fmt.Println is a variadic function too.
Rules
The variadic parameter can only be the last parameter: func yaz(onEk string, degerler ...int). With no arguments, the slice is nil and its len is zero. append(s, other...) uses the same spread syntax.
Practice Average
Write ortalama(sayilar ...float64) float64; return 0 if there are no arguments. Print the result of ortalama(2, 4, 9).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func ortalama(sayilar ...float64) float64 {
if len(sayilar) == 0 {
return 0
}
t := 0.0
for _, n := range sayilar {
t += n
}
return t / float64(len(sayilar))
}
func main() {
fmt.Println(ortalama(2, 4, 9))
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you pass a slice you have to a variadic function?
- topla(...liste)
- topla(*liste)
- topla(liste...) Correct answer
- topla(liste)
Explanation: Writing ... after the slice spreads it into individual arguments; writing just liste is a type error.
2 Spread the slice
liste := []int{4, 5, 6}
fmt.Println(topla(liste____))
liste := []int{4, 5, 6}
fmt.Println(topla(liste...))
Explanation: liste... passes the slice to the variadic parameter as individual arguments.
3 Call and result
| Term | Meaning |
|---|---|
topla(1, 2, 3) |
6 |
topla() |
0 |
topla([]int{4, 5}...) |
9 |
topla(10) |
10 |