GO Go

Go: Functions

What you will learn

How to write functions that return multiple values, how named returns work, and why Go uses error values instead of exceptions.

Basic function

func greet(name string) string {
    return "Hello, " + name
}

Syntax: func keyword, function name, parameters in ( ), return type after them, body in { }.

Multiple return values

Go functions can return more than one value. This is the standard way to handle errors:

import "errors"

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

Callers must handle both values:

result, err := divide(10, 2)
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println(result) // 5

Named return values

You can name the return values. They act as local variables, and a bare return returns their current values:

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

Naked returns are considered bad style in longer functions — use them sparingly, mainly in short functions where they improve readability.

Why not exceptions?

Go's design philosophy: errors are values. You handle them explicitly where they occur, rather than throwing them up the call stack. This makes error paths visible in the code.

Quick check below!