Back to Course
Functions

Functions in Go – Multiple Returns, Variadic, and Defer Tutorial

Basic Function Syntax

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

Multiple Return Values

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

result, err := divide(10, 2)

Variadic Functions

Variadic functions accept a variable number of arguments using ....

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

sum(1, 2, 3, 4) // 10

The defer Keyword

defer schedules a function call to run just before the surrounding function returns — commonly used for cleanup tasks like closing files.

func readFile() {
    file, _ := os.Open("data.txt")
    defer file.Close()
    // read file contents
}

Ready to master real-world Go skills?

Learn Go hands-on with mentor-led, live sessions.

Explore Course