Skip to content

Functions

func add(a int, b int) int {
return a + b
}
// shared type for adjacent parameters
func multiply(a, b int) int {
return a * b
}

This is one of Go’s most distinctive features, and it’s the foundation of Go’s error handling:

func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("divide by zero")
}
return a / b, nil
}

Callers are expected to check the error immediately — the compiler won’t stop you from ignoring it, but go vet and linters like errcheck will flag it.

func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // "naked" return — returns x and y
}

Useful for documenting what a function returns, but use sparingly — it can make longer functions harder to follow.

func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
sum(1, 2, 3) // 6
sum([]int{4, 5}...) // spread a slice

Functions are first-class values in Go — you can pass them around and close over local variables:

func makeCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
counter := makeCounter()
counter() // 1
counter() // 2

Each call to makeCounter produces an independent counter, because each closure captures its own count.