Saturday 4 May 2019

Go language: Return a value from function


Functions in Go can be written zero or more values.

Syntax
func functionName(parameters) returnType{
         statements
        
         return value
}

You can return a value from a function using ‘return’ keyword.

func add(a int, b int) int{
         return a + b
}

HelloWorld.go
package main

import "fmt"

func main() {

 result := add(10, 20)

 fmt.Println("Sum of 10 and 20 is : ", result)

}

func add(a int, b int) int{
 return a + b
}

Output
Sum of 10 and 20 is :  30

Returning multiple values from a function
You can return multiple values from a function­­.

Syntax
func functionName(parameters) (returnType1, … returnType N){
         statements
        
         return value1, … valueN
}

Example
func arithmetic(a int, b int) (int, int, int, int){
         return a + b, a - b, a *b, a / b
}


HelloWorld.go
package main

import "fmt"

func main() {

 addition, subtraction, multiplication, division := arithmetic(10, 20)

 fmt.Println("Sum of 10 and 20 is : ", addition)
 fmt.Println("Subtraction of 10 and 20 is : ", subtraction)
 fmt.Println("Multiplication of 10 and 20 is : ", multiplication)
 fmt.Println("Division of 10 and 20 is : ", division)

}

func arithmetic(a int, b int) (int, int, int, int){
 return a + b, a - b, a *b, a / b
}

Output
Sum of 10 and 20 is :  30
Subtraction of 10 and 20 is :  -10
Multiplication of 10 and 20 is :  200
Division of 10 and 20 is :  0

Named parameters
Just add the names to the return types in function signature.

Example
func arithmetic(a int, b int) (sum int, sub int, mul int, div int){
         sum =  a + b
         sub = a - b
         mul = a *b
         div = a / b

         return
}


HelloWorld.go
package main

import "fmt"

func main() {

 addition, subtraction, multiplication, division := arithmetic(10, 20)

 fmt.Println("Sum of 10 and 20 is : ", addition)
 fmt.Println("Subtraction of 10 and 20 is : ", subtraction)
 fmt.Println("Multiplication of 10 and 20 is : ", multiplication)
 fmt.Println("Division of 10 and 20 is : ", division)

}

func arithmetic(a int, b int) (sum int, sub int, mul int, div int){
 sum =  a + b
 sub = a - b
 mul = a *b
 div = a / b

 return
}

Output
Sum of 10 and 20 is :  30
Subtraction of 10 and 20 is :  -10
Multiplication of 10 and 20 is :  200
Division of 10 and 20 is :  0


A return statement without arguments returns the named return values. This is known as a "naked" return.


Previous                                                 Next                                                 Home

No comments:

Post a Comment