Functions

In Go, a function is a block of code that performs a specific task and returns a result. Functions can take zero or more input parameters and can return zero or more output values.

Here is an example of a simple function that takes two integers as input parameters and returns their sum:

package main

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

func main() {
    result := add(3, 4)
    println(result) // Output: 7
}

Another example of a function is the main the function which is the entry point of the program

package main

func main() {
    println("Hello, World!")
}

Functions can also return multiple values

package main

func swap(a, b int) (int, int) {
    return b, a
}

func main() {
    x, y := 1, 2
    x, y = swap(x, y)
    println(x, y) // Output: 2 1
}

Functions can also have named return values

package main

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

func main() {
    fmt.Println(split(17)) // "4 13"
}

In Go, the function can also have variadic parameters, A variadic function can be called with any number of trailing arguments. For example

package main

import "fmt"

func add(args ...int) int {
    total := 0
    for _, v := range args {
        total += v
    }
    return total
}

func main() {
    fmt.Println(add(1, 2, 3))    // 6
    fmt.Println(add(1, 2, 3, 4)) // 10
}

Last updated