This section contains the Golang closures find output programs (set 1) with their output and explanations.
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)
}
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)
}
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)
}
Program 4:
package main
import "fmt"
func main() {
var num = 0
square := func() {
fmt.Println("Num: ", num)
num++
if num == 5 {
return
}
square()
}
square()
}
Program 5:
package main
import "fmt"
func main() {
var num = 0
square := func() {
fmt.Println("Num: ", num)
num++
if num == 5 {
return
}
this()
}
square()
}
Answer Program 1:
Output:
Explanation:
The code is correct, we create a closure function named square() which is calculating the square of the given number.
Answer Program 2:
Output:
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.
Answer Program 3:
Output:
Explanation:
The above program will generate a syntax error because we cannot create a closure function outside the function.
Answer Program 4:
Output:
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.
Answer Program 5:
Output:
Explanation:
The above program will generate a syntax error because "this" is not defined in the program.
need an explanation for this answer? contact us directly to get an explanation for this answer