(Go Lang) Variadic Functions (GBEN)

Go by Example

Example

  • Like in Lisp
  • slice... syntax when you pass to a function

// Variadic functions can be called with any number of trailing arguments. For
// example, fmt.Println is a common variadic function.
// Run code
// Here’s a function that will take an arbitrary number of ints as arguments.
sum := func (nums ...int) {
  fmt.Print(nums, " ")
  total := 0
  for _, num := range nums {
    total += num
  }
  fmt.Println(total)
}
// Variadic functions can be called in the usual way with individual arguments.
sum(1, 2)
sum(1, 2, 3)
// If you already have multiple args in a slice, apply them to a variadic function using func(slice...) like this.
nums := []int{1, 2, 3, 4}
sum(nums...)
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10

Attribution

Leave a Reply

Your email address will not be published. Required fields are marked *