Saturday 4 May 2019

Go Language: return Error from a function


Go functions return multiple values. Using this feature, most of the Go functions return error value as the last value returned by the function.

For example, below function calculate sum of two integers a and b and a nil, if the numbers are >= 0, else return 0 and an error message.

func add(a int, b int) (int, error) {
         if a < 0 || b < 0 {
                  return 0, fmt.Errorf("sum pf negative numbers is not supported")
         }

         return a + b, nil
}

‘nil’ is like null in other programming languages like Java.

App.go
package main

import "fmt"

func main() {
 result1, err1 := add(10, 20)

 if err1 != nil {
  fmt.Println(err1)
 } else {
  fmt.Println("Sum of 10 and 20 is : ", result1)
 }

 result2, err2 := add(0, -1)

 if err2 != nil {
  fmt.Println(err2)
 } else {
  fmt.Println("Sum of 0 and -1 is : ", result2)
 }
}

func add(a int, b int) (int, error) {
 if a < 0 || b < 0 {
  return 0, fmt.Errorf("sum pf negative numbers is not supported")
 }

 return a + b, nil
}

Output
Sum of 10 and 20 is :  30
sum pf negative numbers is not supported



Previous                                                 Next                                                 Home

No comments:

Post a Comment