Fundamentals

Functions

Define functions, pass values, return multiple results, use variadic parameters, treat functions as values, and understand closures.

What you will learn

Functions are how you give a piece of logic a name so you can reuse it and read it. This lesson covers the syntax for parameters and results, Go's habit of returning several values at once, variadic parameters, and how functions can be stored in variables and capture state, which is what a closure is.

Why functions

Without functions you copy and paste the same logic wherever you need it, and every fix has to be made in every copy. A function names a task, takes inputs, and returns outputs, so the calling code reads like a description of what is happening.

Declaring a function

func add(a int, b int) int {
    return a + b
}
PartMeaning
funcStarts a function declaration
addThe function's name
(a int, b int)Parameters, each written name first, then type
int after the parenthesesThe type of the result
return a + bSends a value back to the caller

When consecutive parameters share a type, you can write the type once:

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

Call it like this:

func main() {
    sum := add(3, 4)
    fmt.Println(sum) // 7
}

A function with no result simply omits the result type:

func greet(name string) {
    fmt.Println("Hello,", name)
}

If a function promises a result and some path does not return one, the compiler stops you with missing return.

Arguments are copies

When you call a function, Go copies each argument into the parameter. Changing a parameter inside the function does not change the caller's variable:

func double(n int) {
    n = n * 2
}

func main() {
    x := 5
    double(x)
    fmt.Println(x) // still 5
}

This is a rule you will rely on, and the pointers lesson shows how to let a function change the caller's value on purpose.

Multiple return values

In many languages a function returns one thing, so you wrap extra results in an object. Go functions can return several values directly:

func checkServerHealth(serverID int) (string, bool) {
    // a real program would query the server here
    return "server is healthy", true
}

func main() {
    message, online := checkServerHealth(101)
    fmt.Println(message, "online:", online)
}

The result types go in parentheses. The caller receives all of them, in order, and must accept every value, or discard one with the blank identifier _:

message, _ := checkServerHealth(101)

The most common use is returning a result together with an error, which you will study in the errors lesson. For now, here is a first look so the pattern is familiar:

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

result, err := divide(10, 2)

nil means "no error". This "value and error" shape appears everywhere in Go code.

Named results

You can name the results in the signature. They act as variables that start at their zero values:

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

A return with no values, called a naked return, sends back the current values of x and y. Named results are useful as documentation, because (x, y int) tells the reader what comes back, but naked returns make longer functions harder to follow.

Use naked returns only in very short functions. In longer ones, write return x, y so the reader does not have to scroll to find what is returned.

Variadic functions

A function can accept any number of arguments of one type by putting ... before the type:

func sum(numbers ...int) int {
    total := 0
    for _, n := range numbers {
        total += n
    }
    return total
}

fmt.Println(sum())        // 0
fmt.Println(sum(1, 2, 3)) // 6

Inside the function, numbers is a slice of int. To pass an existing slice, add ... after it:

values := []int{4, 5, 6}
fmt.Println(sum(values...)) // 15

fmt.Println itself is variadic, which is why it accepts any number of arguments.

Functions are values

A function can be stored in a variable, passed to another function, and returned from one. The type of a function describes its parameters and results:

func apply(a, b int, operation func(int, int) int) int {
    return operation(a, b)
}

func add(a, b int) int      { return a + b }
func multiply(a, b int) int { return a * b }

func main() {
    fmt.Println(apply(4, 5, add))      // 9
    fmt.Println(apply(4, 5, multiply)) // 20
}

func(int, int) int is a type, meaning "a function that takes two ints and returns an int". Passing functions is how you build callbacks, sorting rules, and configurable behaviour.

Anonymous functions

When a function is needed only once, you can write it without a name, right where it is used:

func main() {
    greet := func(name string) {
        fmt.Println("Hello,", name)
    }
    greet("Cloud Engineer")

    result := func(a, b int) int { return a * b }(3, 4) // defined and called immediately
    fmt.Println(result) // 12
}

Closures

An anonymous function can use variables from the function around it. It keeps access to them even after the outer function has finished. That combination is a closure.

func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    next := counter()
    fmt.Println(next()) // 1
    fmt.Println(next()) // 2
    fmt.Println(next()) // 3

    other := counter()
    fmt.Println(other()) // 1, a separate count
}

Each call to counter() creates its own count, and the returned function remembers it. Closures are useful for small bits of state, such as generating IDs or customising behaviour, but state hidden in a closure can be hard to see, so use them deliberately.

Common mistakes

  • Ignoring a result you needed. The compiler rejects x := f() if f returns two values, so you must handle both.
  • Expecting a function to change the caller's variable. Arguments are copies.
  • Forgetting a return on some path. The compiler reports missing return.
  • Overusing naked returns. Explicit returns are clearer in all but tiny functions.
  • Writing func names with a capital letter by accident. In package main it does no harm, but in a library it exports the function.

Practice

Write a function divide(a, b float64) (float64, error) that returns an error when b is zero. In main, call it twice, once with valid numbers and once dividing by zero, and print either the result or the error.

Summary

A function has a name, typed parameters written name first, and an optional result type. Arguments are copied, so changing a parameter does not affect the caller. Functions can return multiple values, most commonly a result plus an error, and ... lets a function accept any number of arguments. Functions are values you can store and pass around, and a closure is an anonymous function that remembers variables from where it was created.

Official reference: A Tour of Go: Functions.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026