Beginner Fundamentals

Functions

Functions group reusable logic. In Go you declare them with the func keyword.

Declaring a function

List parameters with their types, then the return type.

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

func main() {
    fmt.Println(add(2, 3)) // 5
}

When parameters share a type, you can write it once.

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

Multiple return values

Go functions can return more than one value, a common pattern for results plus status.

func divide(a, b int) (int, int) {
    return a / b, a % b
}

quotient, remainder := divide(17, 5)
fmt.Println(quotient, remainder) // 3 2

Named return values

You can name return values. They act like variables and a bare return sends them back.

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

fmt.Println(split(17)) // 7 10

Named returns can improve readability but keep them short and clear.