SyntaxStudy
Sign Up
Go Function Basics and Multiple Return Values
Go Beginner 1 min read

Function Basics and Multiple Return Values

Functions are first-class citizens in Go. They are declared with the `func` keyword, followed by a name, a parameter list, and one or more return types. Go supports multiple return values, which is the idiomatic mechanism for returning a result alongside an error. This pattern makes error handling explicit and impossible to accidentally ignore. Parameters are passed by value in Go, meaning the function receives a copy of each argument. To modify the caller's data or to avoid copying a large struct, pass a pointer instead. Variadic functions accept a variable number of arguments using the `...Type` syntax, and the arguments are received as a slice inside the function. Named return values can be declared in the function signature, which initialises them to their zero values and allows the use of a bare `return` statement. While named returns can improve documentation, bare returns in long functions reduce readability, so they are best reserved for short functions where the names serve as documentation.
Example
package main

import (
    "errors"
    "fmt"
    "strings"
)

// Multiple return values — result and error
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

// Named return values
func minMax(nums []int) (min, max int) {
    min, max = nums[0], nums[0]
    for _, n := range nums[1:] {
        if n < min { min = n }
        if n > max { max = n }
    }
    return // bare return uses named values
}

// Variadic function
func join(sep string, words ...string) string {
    return strings.Join(words, sep)
}

func main() {
    result, err := divide(10, 3)
    if err != nil {
        fmt.Println("error:", err)
    } else {
        fmt.Printf("10 / 3 = %.4f\n", result)
    }

    _, err = divide(5, 0)
    fmt.Println("divide by zero:", err)

    lo, hi := minMax([]int{3, 1, 4, 1, 5, 9, 2, 6})
    fmt.Printf("min=%d  max=%d\n", lo, hi)

    fmt.Println(join(", ", "Go", "is", "great"))
}