Wednesday, August 12, 2015

Go Functions with Multiple Return Values

Go functions support multiple return values. This feature is used for implementing error handling. 

For beginners recommended article before you proceed:

Introduction to Functions

Let us see a simple function that returns multiple values
[RefCode# 1]:


package main

import "fmt"

func multReturn() (int, string) {
 return 1, "OK"

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


The output of the above code is:

1 OK

Play with the code here

In case you want to ignore one (or a few) of the values then you've the option to use blank identifier _ .
Run this code to understand the use of blank identifier. The same code is reproduced below for your reference.


[RefCode# 1.1]

package main

import "fmt"

func multReturn() (int, string) {
 return 1, "OK"

}
func main() {

 _, stringV := multReturn()
 fmt.Println(stringV)
}


Output

OK

Let us see another sample. [RefCode# 2]
Read the comments to understand it.

package main

import "fmt"

// Function is named swap 
//a, b, c are 3 parameters
// a is of type int, b, c are string
//The function returns int, string, string

func swap(a int, b, c string) (int, string, string) {
 return a, c, b // c is placed before b to swap

}
func main() {
 fmt.Println(swap(1, "Isaac", "Newton"))
 fmt.Println(swap(2, "Albert", "Einstein"))
}

The output of the above code:

1 Newton Isaac 2 Einstein Albert

Play with the code here

Multiple Returns for Error Handling

How can we use multiple return values for error handling? Let us see another example [RefCode# 3].


package main

import (
 "errors"
 "fmt"
)

func age(urAge int) (int, error) {

 if urAge > 120 || urAge < 0 {
  return -1, errors.New("Invalid age")
 } else {
  return urAge, nil
 }
}
func main() {

 if a, e := age(29); e != nil {
  fmt.Println("Error: ", e)
 } else {
  fmt.Println("Age: ", a)
 }
}

Output

Age: 29

Play with the code here

Note about the above code snippet [RefCode# 3]:

  • See import section - "errors"
  • errors.New is used to capture the given error message.
  • By convention, errors are the last return value and have type error, a built-in interface.
  • A nil value in the error position indicates that there was no error.Exercise

Write a program that receives age as an input from the user and returns a classification (such as infant, child, teenager, adult) based on the following conditions:

Age:

  • less than 0 - invalid
  • greater than 0 and less than or equal to 2 - infant
  • greater than 2 and less than or equal to 12 - Child
  • greater than 13 and less than or equal to 19 - Teenage
  • greater than 19 and less than or equal to 120 - Adult
  • greater than 120 - invalid

Solution [RefCode# 4]


package main
import (
 "errors"
 "fmt"
)
func age(urAge int) (string, error) {
    switch {
    case urAge < 0 || urAge > 120:
        return "", errors.New("Invalid age")
    case urAge <= 2:
        return "Infant", nil
    case urAge <= 12:
        return "Child", nil
    case urAge <= 19:
        return "Teenager", nil
    default:
        return "Adult", nil
    }
}
func main() {
    
    var input int
    fmt.Println("Enter your age: ")
    fmt.Scanf("%d", &input)

 if b, e := age(input); e != nil {
    fmt.Println("Error: ", e)
    } else {
    fmt.Println("Age: ", input)
    fmt.Println("Classification: ", b)
    }
}
Output
Did you like this? Please share your views.

No comments:

Post a Comment