Go Function variadic parameter

Introduction

There is a special form available for the last parameter in a Go function:

func add(args  ...int) int { 
    total  := 0 
    for _, v  := range args { 
        total += v 
    } 
    return total 
} 

Usage



package main/*ww  w.  jav a  2s .  com*/

import "fmt" 

func main() { 
    fmt.Println(add(1,2,3)) 
} 
func add(args  ...int) int { 
    total  := 0 
    for _, v  := range args { 
        total += v 
    } 
    return total 
} 

In this example, add is allowed to be called with multiple integers.

This is known as a variadic parameter.

An ellipsis ... before the type name of the last parameter can indicate that it takes zero or more of those parameters.

We can also pass a slice of int array by following the slice with an ellipsis:

func main() { 
    xs  := []int{1,2,3} 
    fmt.Println(add(xs...)) 
} 



PreviousNext

Related