go lang

How to use functions in go?

This tutorial demonstrates how to use functions in golang. To write down the modular code we need functions. A function is a group of a statement which perform the desired task. Every go program must have one function in some cases it may default one which is main(). The function takes one or more input values and returns one or more values as a result.

Pros of using function:
  1. Reducing code duplication.
  2. Decomposing problems into smaller chunks.
  3. Maintainance is easy
  4. Code reusability.
  5. Implementation abstraction.
  6. Modular code.

A function is first class citizens in go language. Functions can be assigned to variables, passed as arguments to functions or returned from functions. This makes the language more flexible. which is like functional programming paradigm.

Go supports first class functions, higher-order functions, user-defined function types, function literals, closures, and multiple return values.

This rich feature set supports a functional programming style in a strongly typed language.

Syntax:-


func <name of function>(<input params comma separated >){
 //  function body

// return statement
}

Simple Example:

package main

import "fmt"

func main() {

    x := 7
    y := 3

    z := addition(x, y)

    fmt.Printf("addition: %d\n", z)
}

func addition(a int, b int) int {

    return a + b
}

Output:

$ go run gofunction.go 
addition: 10

In this example, we defined one function as an addition() which takes two arguments and displays the addition of those two. The addition() function takes two arguments of the same type, go can omit the type of the input parameter.

Let us take example

package main

import "fmt"

func addition(x int, y int) int {

    return x + y
}
// go will omit the type of input parameter
func multiplication(x, y int) int {

    return x * y
}

func main() {

    fmt.Println(addition(5, 4))
    fmt.Println(multiplication(5, 4))
}

In the above example, we demonstrated one more thing that it takes two input parameters and returning a single value using the return statement.

Go Multiple value return from function:

What if you want to return multiple values.

Example go function returns multiple values. Here in this example we have given two parenthesis one is to take input and other one is to return values.

package main

import (
    "fmt"
    "math/rand" // math random to get random value
    "time"   // time API
)
// function which will return the four random values.
func fourrandom() (int, int, int, int) {

    rand.Seed(time.Now().UnixNano())
    a := rand.Intn(20)
    b := rand.Intn(20)
	c := rand.Intn(20)
	d := rand.Intn(20)

    return a, b, c, d
}

func main() {

    a, b, c, d := fourrandom() // result asigning to four variables

    fmt.Println(a, b, c, d)
}

Output:-

$ go run returnmultiplevalues.go 
3 16 19 15
Function with named return variables:

We can specify the name to the variable which we want. We can mentioned that names in the round brackets after the function round brackets.

package main

import "fmt"

// speified named return variable
func decrement(x, y, z int) (a, b, c int) {

    a = x - 1
    b = y - 1
    c = z - 1

    return
}

func main() {

    x, y, z := decrement(10, 100, 1000)

    fmt.Println(x, y, z)
}

Output:-

$ go run namedfunc.go 
9 99 999

In this example, we have a function which decrements its three parameters.

func decrement(x, y, z int) (a, b, c int) 
Anonymous functions in Go:

Anonymous functions are supported by go lang. Anonymous functions are the functions with no name. We have function which takes two input and return addition of two numbers.

package main

import "fmt"

func main() {

	 // defined function which take two input and retunr addition of these two
    addition := func(a, b int) int {
        return a + b
    }(9, 1)

    fmt.Println("9+1 =", addition)
}

Output:-

$ go run anonymousfunc.go 
 9+1 = 10
Variadic function:

A variadic function can accept variable number of parameters. A variadic function accepts an variable number of arguments and all these arguments are stored in a parameter of the slice type. We use the ... (ellipses) operator to define a variadic function.

package main

import "fmt"

func main() {

    a1 := add(1, 2, 3)
    a2 := add(1, 2, 3, 4)
    a3 := add(1, 2, 3, 4, 5)

    fmt.Println(a1, a2, a3)
}
// accept variable number of input param
func add(nos ...int) int {

    result := 0

    for _, n := range nos {
        result += n
    }

    return result
}

Output:

$ go run variadic.go 
 6 10 15

The nos variable is a slice, which contains all values passed to the add function. We loop over the slice and calculate the addition of the parameters.

Recursive function call in go:

Recursive functions are function which calls to itself. Recursive function call themselves to perform desired task. Recursive is used in many cases such as calculate factorial of number.

Example:

package main

import "fmt"

func main() {

    fmt.Println(fact(5))
    fmt.Println(fact(10))
    fmt.Println(fact(3))
}

// take input as number and return the result
func fact(n int) int {

    if n == 0 || n == 1 {
        return 1
    }

    return n * fact(n-1)
}

Output:

$ go run recursive.go 
 120
 3628800
 6
Defer function call:

defer  a statement is a convenient way to execute a piece of code before a function returns, as explained in Golang specification, In Go language, multiple defer statements are allowed in the same program and they are executed in LIFO(Last-In, First-Out) order. The arguments are evaluated when the defer statement executed, not when they called.

package main

import "fmt"

func main() {

    fmt.Println("starting")

    defer greet()

    fmt.Println("ending")
}

func greet() {

    fmt.Println("Good morning")
}

Output:

$ go run defergo.go 
 starting
 ending
 Good morning
Conclusion:

In this tutorial, we learned how to define and use functions and different flavours of function that go language support.

Source Code:
https://github.com/maheshwarLigade/spring-boot-examples
$ git clone https://github.com/maheshwarLigade/GoLanguage-tutorials
$ cd GoLanguage-tutorials
$ go run defergo.go