Golang program to return the values from the block


In this golang article, we will learn how to return the values from the block using external function, an anonymous function.

A block is created using curly braces where the scope of variables remains inside the block and not outside of it.

Example 1

In this Example, two values of x and y are added in the code block and z will be assigned the added value. Then, call the function getResult in which another x and y are added and assigned to z in the code block.

package main

import "fmt"

func main() {
   x := 10
   y := 20

   // Code block
   {
      z := x + y
      fmt.Println("Value of z:", z)
   }
   result := getResult()
   fmt.Println("Result:", result)
}

func getResult() int {
   x := 40
   y := 10

   {
      z := x + y
      return z
   }
}

Output

Value of z: 30
Result: 50

Example 2

In this illustration, 10 is assigned to x and 20 is assigned to y which will be added in the anonymous function and returned to it, the added value will be assigned to z.

package main

import "fmt"

func main() {
   x := 10
   y := 20

   // Code block
   z := func() int {
      return x + y
   }()

   fmt.Println("Value of z:", z)
}

Output

Value of z: 30

Conclusion

We executed and compiled the program of returning the values of block using two Examples. In the first Example, we created two code blocks, in the second code block we returned the value and in the second Example we created an anonymous function which returns the added value.

Updated on: 03-May-2023

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements