How to use Ellipsis (…) in Golang?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

Hello Rahul
Hello Mohit
Hello Rahul
Hello Rohit
Hello Johny

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show
// how to use Ellipsis (…)
package main
  
import (
    "fmt"
)
  
// using a varidic 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)
}

chevron_right


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
78 not found in  [38 56 98]

type of nums is []int
87 not found in  []



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.