Skip to content

Go Functions

Functions are the central building blocks in Go.

1. Basic Function

Here's a function that takes two ints and returns their sum as an int. Go requires explicit returns.

package main
import "fmt"

func plus(a int, b int) int {
    return a + b
}

func main() {
    res := plus(1, 2)
    fmt.Println("1+2 =", res)
}

When multiple consecutive parameters are of the same type, you can omit the type for all but the last one: func plus(a, b, c int) int.

2. Multiple Return Values

Go has built-in support for multiple return values. This feature is used often in idiomatic Go, for example, to return both result and error values from a function.

func vals() (int, int) {
    return 3, 7
}

func main() {
    a, b := vals()
    fmt.Println(a)
    fmt.Println(b)

    // If you only want a subset of the values, use the blank identifier _.
    _, c := vals()
    fmt.Println(c)
}

3. Variadic Functions

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

func sum(nums ...int) {
    fmt.Print(nums, " ")
    total := 0
    for _, num := range nums {
        total += num
    }
    fmt.Println(total)
}

func main() {
    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...)
    nums := []int{1, 2, 3, 4}
    sum(nums...)
}

4. Anonymous Functions and Closures

Go supports anonymous functions, which can form closures.

func intSeq() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

func main() {
    nextInt := intSeq()
    fmt.Println(nextInt()) // 1
    fmt.Println(nextInt()) // 2

    newInts := intSeq()
    fmt.Println(newInts()) // 1 (state is unique to each closure)
}