GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing gobyexample.com — Go by Example: Variadic Functions

Go by Example: Variadic Functions

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

package main
import "fmt"

Here’s a function that will take an arbitrary number of ints as arguments.

func sum(nums ...int) {
    fmt.Print(nums, " ")
    total := 0

Within the function, the type of nums is equivalent to []int. We can call len(nums), iterate over it with range, etc.

    for _, num := range nums {
        total += num
    }
    fmt.Println(total)
}
func main() {

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...)
}
$ go run variadic-functions.go 
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10

Another key aspect of functions in Go is their ability to form closures, which we’ll look at next.

Next example: Closures.

by Mark McGranaghan and Eli Bendersky | source | license

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.