Breaking a problem into functions

Any program beyond a few lines breaks a big problem into smaller ones and solves each one separately. In Go, you do that with functions. A function gives a reusable block of logic a name and a signature: callers know what goes in and what comes out without needing to know how the inside works.

You have been using functions since the first article: main is one, and so is fmt.Println. This article is about writing your own.

Declaring a function

The basic syntax for a function in Go is:

Go
func name(parameters) returnType {    // body}
  • func is the keyword that begins a function declaration.
  • name is the identifier used to call the function.
  • parameters is a comma-separated list of name type pairs: the inputs the function accepts. Can be empty.
  • returnType is the type of the value the function produces. Can be omitted if the function returns nothing.

A concrete example:

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

This function takes a single string parameter and prints a greeting. It returns nothing, so the return type is omitted entirely.

Functions that return nothing

A function that produces no output (sometimes called a void function) omits the return type. main is the clearest example you already know:

Go
func main() {    fmt.Println("Hello, world!")}

main takes no parameters and returns no value. It is the entry point that the Go runtime calls when the program starts. Every executable Go program must have exactly one main function in the main package.

fmt.Println is another function you have called many times. From your program's perspective it is a black box: you pass it values, it writes to standard output, and nothing comes back.

You can write your own void functions the same way:

Go
func printDivider() {    fmt.Println("---")}func logMessage(level string, msg string) {    fmt.Printf("[%s] %s\n", level, msg)}

printDivider takes nothing and produces nothing; it only performs a side effect. logMessage takes two strings and uses them to produce formatted output. Neither returns a value, and Go does not require a return statement at the end of a void function.

Functions that return a value

To return a value, add the return type after the parameter list and use the return statement inside the body:

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

The return type int appears after the closing parenthesis of the parameter list. The return statement exits the function and sends the value back to the caller:

Go
result := add(3, 4)fmt.Println(result) // 7

When two or more consecutive parameters share the same type, Go lets you write the type only once:

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

a and b both have type int, so you only declare it once at the end. This is a common Go convention, and it keeps parameter lists short without losing any information.

Multiple return values

Unlike most languages, Go lets a function return more than one value:

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

The return types are listed together in parentheses. The return statement sends both values back simultaneously. At the call site, you capture them with a multi-assignment:

Go
result, err := divide(10, 3)if err != nil {    fmt.Println("Error:", err)} else {    fmt.Println(result) // 3.3333333333333335}

Returning a result alongside an error is idiomatic Go. Functions don't throw exceptions; they signal failure by returning an error value as a second result, and the caller has to handle it explicitly, right where the call happens.

Named return values

Go also allows you to name the return values directly in the function signature. Named return values act as pre-declared variables inside the function body:

Go
func minMax(nums []int) (min, max int) {    min, max = nums[0], nums[0]    for _, n := range nums {        if n < min {            min = n        }        if n > max {            max = n        }    }    return}

The return types are written as (min, max int): both are int, and both have names. Inside the function, min and max are regular variables initialized to their zero values. The bare return at the end, called a naked return, returns whatever those variables currently hold.

Named return values serve two purposes: they act as lightweight documentation (the name tells the caller what each value represents), and they let short functions use naked returns to avoid repeating the variable names.

Variadic parameters

Most functions declare a fixed number of parameters, and the caller must supply exactly that many arguments. Go also supports variadic parameters, which allow a function to accept any number of arguments for its last parameter. The syntax uses three dots before the type:

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

Inside the function, nums is an ordinary []int slice. You can call sum with zero arguments, one, or a hundred:

Go
fmt.Println(sum())               // 0fmt.Println(sum(1, 2, 3))        // 6fmt.Println(sum(10, 20, 30, 40)) // 100

The variadic parameter must be the last one in the list. If a function needs other parameters, they come first:

Go
func logf(level string, args ...any) {    fmt.Printf("[%s] ", level)    fmt.Println(args...)}

If you already have a slice and want to pass it to a variadic function, expand it with ... at the call site:

Go
nums := []int{1, 2, 3, 4}fmt.Println(sum(nums...)) // 10

Without ..., the compiler would expect a single []int argument and reject the call. The ... operator unpacks the slice into individual arguments.

First-class functions

In Go, functions are first-class values: you can assign them to variables, pass them as arguments to other functions, and return them from functions.

Assigning a function to a variable:

Go
add := func(a, b int) int { return a + b }fmt.Println(add(3, 4)) // 7

A function literal (an anonymous function) is assigned to add like any other value. The variable holds the function itself, not a call to it.

Passing a function as an argument:

Go
func apply(op func(int, int) int, a, b int) int {    return op(a, b)}fmt.Println(apply(add, 3, 4)) // 7

apply takes a function as its first argument. Any function whose signature matches func(int, int) int can be passed in, so the caller chooses the operation and apply runs it.

Returning a function from a function:

Go
func multiplier(factor int) func(int) int {    return func(n int) int {        return n * factor    }}double := multiplier(2)triple := multiplier(3)fmt.Println(double(5)) // 10fmt.Println(triple(5)) // 15

multiplier returns a new function each time it is called. The returned function closes over factor: it captures the variable from the enclosing scope and carries it along. This is called a closure. The closure holds the variable itself, not a copy of its value. Each call to multiplier creates a new factor, so double captures one that holds 2 and triple captures a different one that holds 3. Nothing changes either variable after multiplier returns, so each function keeps multiplying by the value it was created with.

Function types

Every function has a type defined by its signature: the parameter types and return type. When that type appears inline in a declaration it can quickly become hard to read:

Go
func apply(    op func(int, int) int,    transform func(int) int,    a int,) int {    return transform(op(a, a))}

Go lets you define a named type for any function signature using the type keyword:

Go
type BinaryOp func(int, int) inttype Transform func(int) intfunc apply(op BinaryOp, transform Transform, a int) int {    return transform(op(a, a))}

Any function whose signature matches BinaryOp satisfies the type without an explicit conversion:

Go
func add(a, b int) int { return a + b }func double(n int) int { return n * 2 }result := apply(add, double, 3) // double(add(3, 3)) = double(6) = 12fmt.Println(result)             // 12

Named function types serve two purposes: they make complex signatures readable, and they communicate intent. When a parameter is typed BinaryOp, the reader knows the expected shape of the function without parsing func(int, int) int. This helps most when the same function shape recurs across a package: define it once as a type and reference it by name everywhere.

Programs as function orchestration

Look at any Go program and you will see the same pattern: main calls functions, those functions call other functions, and each one handles a single well-defined task. The program's behavior comes from how those calls are composed.

Each function accepts what it needs through its parameters and declares what it produces through its return type, so the signature tells a caller everything it needs to use the function.

Functions are the primary unit of abstraction in Go. Methods, interfaces and goroutines all build on top of them.