3

I am trying to understand, What is difference between 1st and 2nd passing argument in function. In both case methods are functional and compiles.

1)

generateReport(capacities...)

func generateReport(capacities ...float64) {
    for i, cap := range capacities {
        fmt.Printf("Plant %d capacity %.0f\n", i, cap)
    }
}

2)

generateReport(plantCapacities)

func generateReport(capacities []float64) {
    for i, cap := range capacities {
        fmt.Printf("Plant %d capacity %.0f\n", i, cap)
    }
}

Have found few good samples

1) GolangBot - Variadic Function

2) Golang.org - Passing arguments as @Himanshu mentioned.

7urkm3n
  • 6,054
  • 4
  • 29
  • 46
  • The question displays absense of even a minimal research as skimming through any inctoructory material on Go should have covered it. – kostix Feb 18 '18 at 14:43
  • "inctoructory" is't russian word? – 7urkm3n Feb 18 '18 at 16:50
  • It should have been introductory. I'm pretty sure that were Putin's hackers controlling my fat fingers, as they usually do. – kostix Feb 18 '18 at 16:53

1 Answers1

10

According to Golang language specification

If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

variadic functions are used to handle multiple trailing arguments. It can be used to pass slice arguments.

func main(){
  capacities := []float64{1, 2, 3, 4}
  generateReport(capacities...)
}

func generateReport(capacities ...float64) {
    for i, cap := range capacities {
        fmt.Printf("Plant %d capacity %.0f\n", i, cap)
    }
}

Variadic functions can also be called in usual way with individual arguments. It works like spread operator in java script which can take multiple arguments. For eg:-

func main(){
  generateReport(1,2,3,4)
}

func generateReport(capacities ...float64) {
    for i, cap := range capacities {
        fmt.Printf("Plant %d capacity %.0f\n", i, cap)
    }
}
Himanshu
  • 12,071
  • 7
  • 46
  • 61