Returning multiple values from a function in Go

In the previous post we looked at how we can create and use functions in go.

Now lets give a look at how we can return multiple values from a function and use them.
We will modify the function in the previous post to return both minimum and maximum value in the array

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, maximum := calculateMinimumAndMaximum(x)
    fmt.Println("Minimum value is", minimum)
    fmt.Println("Maximum value is", maximum)   
}


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

In the code above, we have a function calculateMinimumAndMaximum which returns two integer values, the minimum and maximum number in the array list.

Now, it is fairly evident in the above code that of the two values returned the first is minimum and the second is maximum. How did we know that? Because we can look at the last return statement of the function, which return minimum and maximum.

But if we do not have access to the source code but know only the method signature

  func calculateMinimumAndMaximum(x []int) (int,int)

how can we know what is the first value and what is the second value.

Go comes to rescue here! We can specify names for our return values in our method signature

so our signature

  func calculateMinimumAndMaximum(x []int) (int,int)

can be converted to

  func calculateMinimumAndMaximum(x []int) (min int, maximum int)

Now we know the first value is minimum and second value is maximum from signature itself.

Here is how the final code looks like now.


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, maximum := calculateMinimumAndMaximum(x)
    fmt.Println("Minimum value is", minimum)
    fmt.Println("Maximum value is", maximum)   
}


func calculateMinimumAndMaximum(x []int) (min int, maximum int) {
    minimum := -1
    max := 0    
    for _, v := range x {
        
        if minimum == -1 || v < minimum {
        
          minimum = v
        }
        
        if max < v {
         
            max = v
        }
    }
    return minimum, max 
}


Pretty Awesome!

~~ Whizdumb ~~

Advertisements

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 ~~

Comparing two maps in Go

Follow the latest of Whizdumb’s journey here.

I have started learning Go these days, and have revived this blog and will be using it to share what all I learn in Go.

Lets start with looking at how we can compare two maps

package main

import "fmt"
import "reflect"
func main() {
var x map[int]int
var y map[int]int
x = make(map[int]int)
y = make(map[int]int)
x[1] = 10
y[1]=10
eq := reflect.DeepEqual(x, y)
if eq {
fmt.Println ("The two maps are equal")
}else{
fmt.Println ("The two maps are not equal")
}
}

In the above code to compare map, we have imported the reflect package, which provides a DeepEqual() method.

We have used reflect.DeepEqual(x,y) where x and y are two maps to be compared and we receive a boolean value as result. We have stored that boolean value in a new variable called eq.

In the above example two maps are equal. You can run the above code here.

The Kick Off

So , I am starting the blogging.. (Some Rhythm there, at the cost of grammar… ;-)) finally after promising myself umpteen number of times that some day I Will. So I start the blog on the 1st day of 10th month of 10th year after the end of 20th century. .. phew, lots of 1s and 0s there. ( I am a SoftE (S/w Engg.) I love binary Values. That damn 20th century ought to be 10th century, consider that a bug, or if you are a developer, a feature.. 😉 ) .

In a recent development a verdict has been delivered on a case “full of landmines” , After all the lord RAMA himself was a party to this case and he has been granted a piece of land on the earth which I thought He CREATED..!!!! . I think this was the “landmine” the judge was talking about, lest the GOD becomes angry for denying him his land and curses him..!!!

Taaalking of GODS… Rajnikant’s (He is a GOD to many, particularly in south of my Country) Film Robot has also been released today, It has some different name in tamil version which I can’t Remember Right Now. The only reason it finds a mention here is because of its budget,  last I heard,  it was 165 crore. (For those hard in maths, there are 7 Zeros in one crore.).

It has been a long week this one, it certainly seemed so with the work load fluctuating like pendulum through the week. Started with light stuff and ending on the verge of a full blown storm which I anticipate in the coming weeks. Next week though our team is off to Goa on Holidays, so the storm will have to wait before striking…!!!

Signed Off

Whiz dumb.