Functions

Define and use functions in Go

#functions #return-values #parameters

Functions

Functions are the building blocks of Go programs.

Basic Function

func greet(name string) {
    fmt.Println("Hello,", name)
}

func add(x int, y int) int {
    return x + y
}

// Short parameter syntax
func multiply(x, y int) int {
    return x * y
}

Multiple Return Values

func swap(x, y string) (string, string) {
    return y, x
}

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

// Usage
result, err := divide(10, 2)
if err != nil {
    log.Fatal(err)
}

Named Return Values

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

Variadic Functions

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

// Usage
result := sum(1, 2, 3, 4, 5)

Discover another handy tool from EditPDF.pro