Open in App
Not now

How to use Ellipsis (…) in Golang?

• Last Updated : 19 Jul, 2021

The three dots () in Golang is termed as Ellipsis in Golang which is used in the variadic function. The function that called with the varying number of arguments is known as variadic function. Or in other words, a user is allowed to pass zero or more arguments in the variadic function. fmt.Printf is the example of the variadic function, it required one fixed argument at the starting after that it can accept any number of arguments.

The last parameter of the variadic function is always using the Ellipsis. It means it can accept any number of arguments.

Example 1:

Go

 // Golang program to show // how to use Ellipsis (…) package main    import "fmt"    func main() {     sayHello()     sayHello("Rahul")     sayHello("Mohit", "Rahul", "Rohit", "Johny") }    // using Ellipsis func sayHello(names ...string) {     for _, n := range names {         fmt.Printf("Hello %s\n", n)     } }

Output:

Hello Rahul
Hello Mohit
Hello Rahul
Hello Rohit
Hello Johny

Example 2:

Go

 // Golang program to show // how to use Ellipsis (…) package main   import (     "fmt" )   // using a variadic function func find(num int, nums ...int) {     fmt.Printf("type of nums is %T\n", nums)     found := false     for i, v := range nums {         if v == num {             fmt.Println(num, "found at index", i, "in", nums)             found = true         }     }     if !found {         fmt.Println(num, "not found in ", nums)     }     fmt.Printf("\n") } func main() {       // calling the function with     // variable number of arguments     find(89, 89, 90, 95)     find(45, 56, 67, 45, 90, 109)     find(78, 38, 56, 98)     find(87) }

Output:

type of nums is []int
89 found at index 0 in [89 90 95]

type of nums is []int
45 found at index 2 in [56 67 45 90 109]

type of nums is []int