Functions in GO

Functions in GO

ยท

2 min read

Functions

A function is used to break a large problem into smaller tasks.

We can invoke a function several times that means it provoke reusability.

Function parameters, return values, with types together is called function signature.

In Go we cannot declare a function inside another function.

Go Function Example

package main

import "fmt"

func add() { // declaring a function
    var num1 int = 15
    var num2 int = 25

    var sum = num1 + num2

    fmt.Println(sum)
}

func main() {
    add() // calling the function
}

Output :-

image.png

Go Function with return

package main

import "fmt"

func add() int {
    var num1 int = 100
    var num2 int = 506

    var sum = num1 + num2

    return sum
}

func main() {
    fmt.Println(add())
}

Output :-

image.png

Go function with Multiple Return

package main

import "fmt"

func add() (int, int, int) {
    var num1 int = 100
    var num2 int = 506

    var sum = num1 + num2

    return num1, num2, sum
}

func main() {
    fmt.Println(add())
}

Output :-

image.png

Function with arguments

package main

import "fmt"

func add(a, b int) int {
    var sum = a + b
    return sum
}
func main() {
    fmt.Println(add(18, 14))
}

Output :-

image.png

Recursion in Go

Calling one function from the same function is known as recursion.

Recursion Example :-

I am also going with the popular same factorial number example for recursion. ๐Ÿ˜‚๐Ÿ˜‚

package main

import "fmt"

func factorial(number int) int {
    if number == 0 {
        return 1
    }
    return number * factorial(number-1)
}
func main() {
    fmt.Println(factorial(5))
}

Output :-

image.png

Go Closure

A closure is a function which refers reference variable from outside its body.
The function may access and assign to the referenced variable.

Go closure Example

Now for this example, we create an anonymous function which act as function closure.

Anonymous function :- A function which has no name is called anonymous function.

package main

import "fmt"

func main() {
    num := 10
    squareNum := func() int {
        num *= num
        return num
    }
    fmt.Println(squareNum())
    fmt.Println(squareNum())
}

Output :-

image.png

Did you find this article valuable?

Support Gautam Jha by becoming a sponsor. Any amount is appreciated!

ย