Variadic. Sometimes a Go method must receive zero, one, or many arguments, and they can be specified directly. This is a variadic method, and it uses 3 periods in its argument list.
With variadic methods, arguments are received as a slice. But to pass a slice to a variadic method, we must use special syntax to ensure the program compiles.
Example. This Go program shows 3 functions that have variadic argument lists, and it calls the functions in a variety of ways with different arguments.
Part 1 This func receives zero, one or more string arguments, and it writes the "colors" slice with fmt.Println.
Part 3 The any type means the same thing as interface{} and it refers to any type. We can use "any" in a variadic func.
Part 4 We call Example1 with direct arguments, and with a string slice (by following the slice with 3 periods).
Part 5 If we want, we can omit all arguments to a variadic method, and it will be called correctly.
Part 6 If "any" is the type of the variadic argument, we can pass various types to the method.
package main
import "fmt"
func Example1(colors ...string) {
// Part 1: receive a string slice of any number of arguments.
fmt.Println("Colors are", colors)
}
func Example2(values ...int) {
// Part 2: an int slice can be received.
fmt.Println("Values:")
for v := range values {
fmt.Println(v)
}
}
func Example3(items ...any) {
// Part 3: we can use any to mean any object like interface{}.
fmt.Println("Items are", items)
}
func main() {
// Part 4: call variadic method with arguments directly, and with a slice.
Example1("blue", "red", "yellow")
c := []string{"orange", "green"}
Example1(c...)
// Part 5: it is possible to use no arguments to a variadic method.
Example2(10, 20, 30)
Example2()
// Part 6: for any, we can pass any values.
Example3("bird", 10, nil)
}Colors are [blue red yellow]
Colors are [orange green]
Values:
0
1
2
Values:
Items are [bird 10 <nil>]
With variadic methods, we can receive zero, one or many arguments, and these arguments are conveniently received as a slice. A slice can be passed to a variadic method with some special syntax.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.