WeCodeAcademy

Go Variadic Functions and Function Values

ExampleGo
package main

import "fmt"

func sum(nums ...int) int {
  total := 0
  for _, n := range nums {
    total += n
  }
  return total
}

func apply(nums []int, f func(int) int) []int {
  out := make([]int, 0, len(nums))
  for _, n := range nums {
    out = append(out, f(n))
  }
  return out
}

func main() {
  fmt.Println(sum(), sum(1, 2, 3))
  values := []int{4, 5, 6}
  fmt.Println(sum(values...))
  fmt.Println(apply(values, func(n int) int { return n * n }))
}
Output
0 6
15
[16 25 36]

nums ...int collects any number of arguments into a slice. Functions are values in Go, so you can pass them around, as apply does.

Quick check

What does the ... before values do in sum(values...)?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.