ZetCode

Golang return keyword

last modified May 7, 2025

This tutorial explains how to use the return keyword in Go. We'll cover function returns with practical examples of different return scenarios.

The return statement terminates execution of the current function and optionally returns one or more values to the caller. It's fundamental to function behavior in Go.

In Go, return can return single values, multiple values, or nothing. It always exits the function immediately when executed. Functions with return types must return values of that type.

Basic function return

The simplest use of return exits a function and returns a single value. This example demonstrates a basic addition function.

basic_return.go
package main

import "fmt"

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

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

The add function returns the sum of two integers. The return statement calculates and returns the result. The function exits immediately.

Multiple return values

Go supports returning multiple values from functions. This example shows how to return and receive multiple values.

multiple_return.go
package main

import "fmt"

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

func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result)
    }
}

The function returns both a result and an error value. This is a common Go pattern for error handling. The caller receives both values separately.

Named return values

Go allows naming return values for clarity. These variables are automatically returned when using a bare return statement.

named_return.go
package main

import "fmt"

func rectProps(length, width float64) (area, perimeter float64) {
    area = length * width
    perimeter = 2 * (length + width)
    return // naked return
}

func main() {
    a, p := rectProps(5, 3)
    fmt.Printf("Area: %.2f, Perimeter: %.2f\n", a, p)
}

The return values area and perimeter are declared in the function signature. The bare return returns their current values. This improves code readability in some cases.

Early return for error handling

return is often used for early exits in error conditions. This example demonstrates the common Go pattern of checking errors first.

early_return.go
package main

import (
    "fmt"
    "os"
)

func processFile(filename string) error {
    file, err := os.Open(filename)
    if err != nil {
        return err // early return on error
    }
    defer file.Close()
    
    // Process file contents here
    fmt.Println("File processed successfully")
    return nil
}

func main() {
    err := processFile("test.txt")
    if err != nil {
        fmt.Println("Error:", err)
    }
}

The function returns immediately if file opening fails. This pattern keeps the happy path unindented and makes error conditions clear.

Returning functions

Go functions can return other functions. This example shows a function that returns a closure with access to its scope.

return_function.go
package main

import "fmt"

func multiplier(factor int) func(int) int {
    return func(x int) int {
        return x * factor
    }
}

func main() {
    double := multiplier(2)
    triple := multiplier(3)
    
    fmt.Println("Double of 5:", double(5))
    fmt.Println("Triple of 5:", triple(5))
}

The multiplier function returns another function. The returned closure remembers the factor value from the outer scope.

Returning structs

Functions can return complex types like structs. This example demonstrates returning a custom struct type.

return_struct.go
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func createPerson(name string, age int) Person {
    return Person{
        Name: name,
        Age:  age,
    }
}

func main() {
    p := createPerson("Alice", 30)
    fmt.Printf("%+v\n", p)
}

The function returns a fully initialized Person struct. The caller receives the complete struct value. Struct returns are common in Go for complex data.

Returning pointers

Functions can return pointers to values. This is useful for large structs or when you need to modify the returned value.

return_pointer.go
package main

import "fmt"

func createCounter() *int {
    count := 0
    return &count
}

func main() {
    counter := createCounter()
    *counter++
    fmt.Println("Count:", *counter)
}

The function returns a pointer to a local variable. In Go, this is safe because the compiler performs escape analysis. The caller can modify the value through the pointer.

Source

Go language specification

This tutorial covered the return keyword in Go with practical examples of different return patterns in functions.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.