Getting Started

Functions

Write Go functions with multiple return values, named returns, and variadic parameters.

Go Functions

Go functions can return multiple values — this is used extensively for error handling (return value + error).

Error Handling

Go's idiomatic error handling: functions return (result, error). The caller checks if error is nil.

This is different from exceptions — errors are explicit values, not exceptional cases.

Named Return Values

You can name return values and use return with no arguments (naked return). Use sparingly — can hurt readability.

Variadic Functions

Use ... to accept a variable number of arguments.

First-Class Functions

Functions are values in Go. You can assign them to variables, pass them as arguments, and return them from functions.

Example

go
package main

import (
    "errors"
    "fmt"
    "math"
)

// Multiple return values
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide 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 // naked return
}

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

// First-class functions
type MathFunc func(float64) float64

func apply(f MathFunc, x float64) float64 {
    return f(x)
}

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

    _, err = divide(5, 0)
    if err != nil {
        fmt.Println("Error:", err)  // cannot divide by zero
    }

    // Named returns
    nums := []int{3, 1, 4, 1, 5, 9, 2, 6}
    min, max := minMax(nums)
    fmt.Println("min:", min, "max:", max)

    // Variadic
    fmt.Println(sum(1, 2, 3, 4, 5))  // 15
    slice := []int{10, 20, 30}
    fmt.Println(sum(slice...))        // spread slice

    // First-class function
    double := func(x float64) float64 { return x * 2 }
    fmt.Println(apply(double, 5))    // 10
    fmt.Println(apply(math.Sqrt, 16)) // 4
}
Try it yourself — GO