Working with functions in Golang

Follow the latest of Whizdumb’s journey here.

Functions are an integral part of any language, they help not just in building a functionality but also make the code cleaner, less buggy and easy to understand.

Lets explore a function in Go language, Here is a program which return the minimum of the given positive numbers

package main
import "fmt"
func main() {    
 x := []int{
    48,96,86,68,
    57,82,63,70,
    37,34,83,27,
    19,97, 9,17,
}    
    minimum := -1    
    for _, v := range x {
        
        if minimum == -1 || v < minimum {
        
          minimum = v
        }
    }
    fmt.Println(minimum)
}

We just used few functions here. main() is a function which gets invoked when we run this code. The main() like in C or Java forms the entry point from where the code starts executing.

We also used another function Println which is part of “fmt” package which we imported.

Now lets create our own function. Lets extract the logic to calculate the minimum out to another function and print it. Here is how it looks like

package main
import "fmt"

func main() {
    
 x := []int{
    48,96,86,68,
    57,82,63,70,
    37,34,83,27,
    19,97, 9,17,
}
  calculateMinimum(x)
}

func calculateMinimum(x []int) {
    minimum := -1
    for _, v := range x {
        
        if minimum == -1 || v < minimum {
        
          minimum = v
        }
    }
    fmt.Print(minimum)    
}

We have created a function called calculateMinimum() which accepts an array of integers and returns nothing.

Lets now modify it to return a value

package main
import "fmt"
func main() {
     x := []int{
    48,96,86,68,
    57,82,63,70,
    37,34,83,27,
    19,97, 9,17,
}
    minimum := calculateMinimum(x)
    fmt.Println("Minimum value is", minimum)
}

func calculateMinimum(x []int) int {
    minimum := -1
    for _, v := range x {
       if minimum == -1 || v < minimum {   
          minimum = v
        }
    }
    return minimum    
}

Here, notice the change in signature of the function from func calculateMinimum(x []int) to func calculateMinimum(x []int) int the extra int in the end tells the compiler that we are expecting an int value to be returned from this function.

We are assigning the returned value to minimum variable in the main function and using it to print the minimum value.

In the next blog we will see how we can return multiple values from a function.

Sd:
~~ Whizdumb ~~

Advertisements

2 thoughts on “Working with functions in Golang

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s