Functions
Functions in Go are simple and powerful: they can return several values, take a variable number of arguments, be stored in variables, and capture variables from around them (closures). Multiple return values are the foundation of Go's error handling.
Basics
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func greet(name string) {
fmt.Println("Hello,", name)
}
func area(width, height float64) float64 { // same type: write it once
return width * height
}
func main() {
greet("Asha")
fmt.Println(add(2, 3), area(2.5, 4))
}Hello, Asha 5 10
Types come after names: name string, and the return type after the parameter list. Go reads left to right: "function add takes a and b, both int, and returns an int".
Multiple return values
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
func minMax(nums []int) (int, int) {
lo, hi := nums[0], nums[0]
for _, n := range nums {
lo = min(lo, n)
hi = max(hi, n)
}
return lo, hi
}
func main() {
if q, err := divide(10, 4); err == nil {
fmt.Println("10 / 4 =", q)
}
if _, err := divide(1, 0); err != nil {
fmt.Println("error:", err)
}
lo, hi := minMax([]int{21, 34, 18, 29})
fmt.Println("min", lo, "max", hi)
}10 / 4 = 2.5 error: cannot divide by zero min 18 max 34
The pattern value, err := f() followed by if err != nil is the heart of Go. A function that can fail returns its result and an error; nil means success. min and max are built in (Go 1.21+).
Named results
package main
import (
"fmt"
"strings"
)
// Named results document what's returned and start at their zero values.
func split(email string) (user, domain string, ok bool) {
at := strings.LastIndex(email, "@")
if at < 1 {
return // "naked" return: returns user, domain, ok as they are
}
return email[:at], email[at+1:], true
}
func main() {
fmt.Println(split("asha@example.com"))
u, d, ok := split("not-an-email")
fmt.Printf("%q %q %v\n", u, d, ok)
}asha example.com true "" "" false
Named results are nice documentation; naked returns are best kept to very short functions.
Variadic functions
A ... parameter accepts any number of arguments, received as a slice:
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func logf(level string, format string, args ...any) {
fmt.Printf("["+level+"] "+format+"\n", args...)
}
func main() {
fmt.Println(sum(), sum(1, 2), sum(1, 2, 3, 4))
scores := []int{90, 85, 77}
fmt.Println(sum(scores...)) // spread a slice into the arguments
logf("INFO", "user %s logged in from %s", "asha", "10.0.0.5")
}0 3 10 252 [INFO] user asha logged in from 10.0.0.5
fmt.Println itself is variadic: func Println(a ...any). any means "a value of any type".
Arguments are copied
Go passes everything by value: the function gets a copy. To let a function change the caller's variable, pass a pointer:
package main
import "fmt"
func resetCopy(n int) { n = 0 }
func resetReal(n *int) { *n = 0 }
func main() {
count := 42
resetCopy(count)
fmt.Println("after resetCopy:", count)
resetReal(&count)
fmt.Println("after resetReal:", count)
}after resetCopy: 42 after resetReal: 0
&count is the address of count; *n follows the pointer. Unlike C, there's no pointer arithmetic, and the garbage collector frees memory for you, so Go pointers are safe. Slices and maps already contain a pointer to their data, so a function can change their elements without you passing a pointer (more in the next lesson).
Functions are values
Functions can be stored in variables, passed to other functions and returned from them:
package main
import (
"fmt"
"slices"
"strings"
)
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() {
double := func(x int) int { return x * 2 }
fmt.Println(apply([]int{1, 2, 3}, double))
fmt.Println(apply([]int{1, 2, 3}, func(x int) int { return x * x }))
names := []string{"ravi", "Asha", "lee", "Mira"}
slices.SortFunc(names, func(a, b string) int {
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
})
fmt.Println(names)
}[2 4 6] [1 4 9] [Asha lee Mira ravi]
The anonymous function passed to slices.SortFunc decides the order: here, alphabetical ignoring case.
Closures
A function literal can use variables from the function around it, and it keeps them alive:
package main
import "fmt"
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
next := counter()
fmt.Println(next(), next(), next())
other := counter() // a separate count
fmt.Println(other(), next())
}1 2 3 1 4
Each call to counter creates a new count variable, and the returned function holds on to it. Closures are used everywhere in Go: HTTP handlers, sorting, retry helpers and middleware.
Recursion
package main
import "fmt"
func factorial(n uint64) uint64 {
if n <= 1 {
return 1
}
return n * factorial(n-1)
}
func main() {
fmt.Println(factorial(10), factorial(20))
}3628800 2432902008176640000
Go's stacks grow automatically, so deep recursion that would crash C usually works. A loop is still faster.
Methods and init, briefly
Two special kinds of functions you'll meet soon:
- Methods are functions attached to a type:
func (a Account) Balance() int. They're covered in Structs and methods. func init()runs automatically beforemain, once per package. It's used for setup like registering plugins; keep it small.
Practice
- Write
func stats(nums ...float64) (mean, stddev float64)and test it. - Write
func parseKV(s string) (key, value string, err error)for input like"port=8080", returning an error if there's no=. - Write
func filter(nums []int, keep func(int) bool) []intand use it to keep only the even numbers. - Write
func makeMultiplier(n int) func(int) intand createdoubleandtriplewith it.
1.What's the usual way a Go function reports failure?
2.How do you pass a slice to a variadic function sum(nums ...int)?
3.A function receives n int and sets n = 0. What happens to the caller's variable?
4.What does counter() return in the closures example?