How to Use Variadic Functions in Golang

Created
Modified

Variadic Function

A variadic function is one that can be called with varying numbers of arguments. The most familiar examples are fmt.Printf and its variants.

package main

import "fmt"

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

func main() {

  fmt.Println(add())
  fmt.Println(add(2))
  fmt.Println(add(4, 5, 6))

  values := []int{1, 2, 3, 4}
  fmt.Println(add(values...)) // "10"
}
$ go run main.go
0
2
15
10

Examples

Join concatenates the elements of its first argument to create a single string.

package main

import "fmt"

func join(sep string, elems ...string) string {
  var s string
  for i, v := range elems {
    if i == 0 {
      s = v
    } else {
      s += sep + v
    }
  }
  return s
}
func main() {

  s := join(",", "A", "B", "C")
  fmt.Println(s)
  fmt.Println(join(",", "A"))
  fmt.Println(join(","))

}
$ go run main.go
A,B,C
A

Benchmark

After running the benchmark, we receive the following results:

func BenchmarkJoin(b *testing.B) {

  s := []string{"A", "B", "C"}

  for i := 0; i < b.N; i++ {
    join(",", s...) // 86.54 ns/op
    // strings.Join(s, ",") 46.82 ns/op
  }

}
$ go test -bench=. --count=1
join   86.54 ns/op
Join   46.82 ns/op

Related Tags