Functions
Basic syntax
Section titled “Basic syntax”func add(a int, b int) int { return a + b}
// shared type for adjacent parametersfunc multiply(a, b int) int { return a * b}Multiple return values
Section titled “Multiple return values”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.
Named return values
Section titled “Named return values”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.
Variadic functions
Section titled “Variadic functions”func sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total}
sum(1, 2, 3) // 6sum([]int{4, 5}...) // spread a sliceFunctions as values, and closures
Section titled “Functions as values, and closures”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() // 1counter() // 2Each call to makeCounter produces an independent counter, because each closure captures its own count.