7urkm3n
7urkm3n

Reputation: 6321

Go variadic function argument passing

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.

Upvotes: 3

Views: 2214

Answers (1)

Himanshu
Himanshu

Reputation: 12685

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

Upvotes: 10

Related Questions