Skip to main content

Functions and Packages

Functions are the building blocks of Go programs.

Function Syntax

func add(x int, y int) int {
    return x + y
}
If parameters share a type, you can omit the type for all but the last.
func add(x, y int) int {
    return x + y
}

Multiple Return Values

Go functions can return multiple results. This is commonly used to return a result and an error.
func swap(x, y string) (string, string) {
    return y, x
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

Named Return Values

Return values can be named. If so, they are treated as variables defined at the top of the function. A “naked” return statement returns the named return values.
func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return // returns x, y
}
Best Practice: Use named returns only for short functions. In longer functions, they can harm readability.

Variadic Functions

Functions can take a variable number of arguments.
func sum(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}

func main() {
    fmt.Println(sum(1, 2))
    fmt.Println(sum(1, 2, 3))
    
    nums := []int{1, 2, 3, 4}
    fmt.Println(sum(nums...)) // spread slice
}

Packages

Every Go program is made up of packages. Programs start running in package main.

Imports

import (
    "fmt"
    "math/rand"
)

Exported Names

In Go, a name is exported if it begins with a capital letter. For example, Pizza is an exported name, as is Pi, which is exported from the math package. pizza and pi do not start with a capital letter, so they are not exported.
func main() {
    fmt.Println(math.Pi) // OK
    // fmt.Println(math.pi) // Error: cannot refer to unexported name math.pi
}

Package Initialization (init)

Variables can be initialized during declaration, but init functions allow for more complex initialization logic.
package main

import "fmt"

var myVar int

func init() {
    fmt.Println("Initializing...")
    myVar = 42
}

func main() {
    fmt.Println("Main started, myVar =", myVar)
}
init functions run automatically before main.