Golang Closures | Find Output Programs | Set 1

This section contains the Golang closures find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on September 24, 2021

Program 1:

package main

import "fmt"

func main() {
	var result = 0

	square := func(num int) int {
		return num * num
	}

	result = square(10)
	fmt.Println("Result: ", result)

	result = square(20)
	fmt.Println("Result: ", result)
}

Output:

Result:  100
Result:  400

Explanation:

The code is correct, we create a closure function named square() which is calculating the square of the given number.


Program 2:

package main

import "fmt"

func main() {

	var result = 0
	var num = 10

	var ptr1 *int = &num
	var ptr2 **int = &ptr1

	square := func(num int) int {
		return num * num
	}

	result = square(**ptr2)
	fmt.Println("Result: ", result)
}

Output:

Result:  100

Explanation:

In the above code, we created a closure function square() to calculate the square of the given number. And, we created a pointer ptr1 initialized with the address of num variable, and pointer-to-pointer ptr2 initialized with the address of pointer ptr1. Then we called created a closure function by dereferencing the pointer to access the value of the num variable and printed the square of the number.


Program 3:

package main
import "fmt"

square := func(num int) (int){  
      return num*num;
}

func main() {  
    var result = 0
    var num = 10
    
    var ptr1 *int = &num
    var ptr2 **int = &ptr1
   
    result = square(**ptr2)
    fmt.Println("Result: ",result)  
}

Output:

./prog.go:4:1: syntax error: non-declaration statement outside function body

Explanation:

The above program will generate a syntax error because we cannot create a closure function outside the function.


Program 4:

package main

import "fmt"

func main() {
	var num = 0

	square := func() {
		fmt.Println("Num: ", num)
		num++
		if num == 5 {
			return
		}
		square()
	}

	square()
}

Output:

./prog.go:14:3: undefined: square

Explanation:

The above program will generate syntax error because here we tried to call closure function from itself. But reference "square" is not accessible inside its body.


Program 5:

package main

import "fmt"

func main() {
	var num = 0

	square := func() {
		fmt.Println("Num: ", num)
		num++
		if num == 5 {
			return
		}
		this()
	}

	square()
}

Output:

./prog.go:14:3: undefined: this

Explanation:

The above program will generate a syntax error because "this" is not defined in the program.

Golang Find Output Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.