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.
This Go program shows 3 functions that have variadic argument lists, and it calls the functions in a variety of ways with different arguments.
func
receives zero, one or more string
arguments, and it writes the "colors" slice with fmt.Println
.int
slice) as well. Here we use a for-range
loop to print out the integers.interface
{} and it refers to any type. We can use "any" in a variadic func
.Example1
with direct arguments, and with a string
slice (by following the slice with 3 periods).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.