Functions in Go

Blocks of code that can be repeatedly invoked in a program.

Syntax
func function_name(parameter1 type, parameter2 type) return_type {
    // coode
    return value 
} 

Here is how to define and call a function that adds to two numbers. Parameters to the add function are x int and y int x, y is the parameter name and type preceding it is it’s type. return statement returns a value. A return type or a return statement is not mandatory.

Example
func add(x int, y int) int {
  return x + y
} 
fmt.Println(add(1,2)) // Outputs: 3
fmt.Println(add(2,3)) // Outputs: 5

Recursion

Go also supports recursion, where a function calls itself with an exit condition. Exit condition is used to avoid infinite loops.

Example
func fact(n int) int {
    // exit condition
    if n == 0 {
        return 1
    }
    // function calling itself
    return n * fact(n-1)
}
fmt.Println(fact(5)) // Outputs: 120
Last updated on