Go Functions

Basic Function

Functions in Go are declared with the func keyword:

func greet() {
    fmt.Println("Hello, Go!")
}

Call it with:

greet()

Function with Parameters

Basic Structure:

func name(parameters) return_value_type {
    // code block
}

Examples

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

Types must be specified for each parameter, unless they are the same for all:

func multiply(x, y int) int {
    return x * y
}

Multiple Return Values

Functions can return multiple values:

Basic Structure:

func name(paramters) (return_value_types) {
    // code block
}
Loading...
Output:

Named Return Values

Improve code readability and allows an implicit return using return without explicitly specifying values

  • Makes the purpose of each return value clearer
  • Useful when you have multiple return values
  • Allows step-by-step assignments and a final return without listing variables again
Loading...
Output:

Variadic Functions

Use ... to accept any number of arguments:

func sum(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}
total := sum(1, 2, 3, 4)

Function Types and Assignments

Functions can be assigned to variables or passed as arguments:

func sayHi() {
    fmt.Println("Hi")
}

var f func() = sayHi    // Defines f as a variable of type func(), and assigns the function definition sayHi
f()   // call the function through variable

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic