Go Course

Go Functions: Declaration, Multiple Returns, Variadic

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Basic Function Declaration

func greet(name string) string {
    return "Hello, " + name + "!"
}

func main() {
    msg := greet("Alice")
    fmt.Println(msg) // Hello, Alice!
}

Multiple Return Values

Go functions can return multiple values — a common pattern for returning a result along with an error:

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

result, err := divide(10, 3)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Printf("Result: %.2f
", result)
}

Named Return Values

func minMax(arr []int) (min, max int) {
    min, max = arr[0], arr[0]
    for _, v := range arr[1:] {
        if v < min { min = v }
        if v > max { max = v }
    }
    return // naked return
}

Variadic Functions

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

fmt.Println(sum(1, 2, 3))       // 6
fmt.Println(sum(1, 2, 3, 4, 5)) // 15

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

Defer

func readFile(path string) {
    f, _ := os.Open(path)
    defer f.Close() // runs when function returns

    // work with file...
}