How to use Ellipsis (...) in Golang?


Example

package main

import "fmt"

func demoEllipsis(arg ...int) {
	fmt.Println("Length of Arguments: ",len(arg))
    fmt.Printf("Arguments: %+v\n",arg)
}

func main() {
    fmt.Println("\nExample I")
    demoEllipsis([]int{1,2,3}...)
    
	fmt.Println("\nExample II")
    demoEllipsis(1,2,3,4,5)
    
	fmt.Println("\nExample III")
    demoEllipsis()
	
	fmt.Println("\nDynamic Array")
	intArray := [...] int {1,2,3,4,5,6,7}
	fmt.Println("Length: ",len(intArray))
	fmt.Println("Capacity: ",cap(intArray))
    fmt.Println(intArray)
	
	fmt.Println("\nInterface")
	interfaceEx := []interface{}{"Australia", "Canada", "Japan"}	
	fmt.Println(interfaceEx...)
}

Output

Example I
Length of Arguments:  3
Arguments: [1 2 3]

Example II
Length of Arguments:  5
Arguments: [1 2 3 4 5]

Example III
Length of Arguments:  0
Arguments: []

Dynamic Array
Length:  7
Capacity:  7
[1 2 3 4 5 6 7]

Interface
Australia Canada Japan
Most Helpful This Week