This section contains the Golang closures find output programs (set 2) with their output and explanations.
Program 1:
package main
import "fmt"
func main() {
var num=0
counter := func() (){
fmt.Println("Num: ",num)
num++
if(num==5){
return
}
func()
}
counter()
}
Program 2:
package main
import "fmt"
func main() {
var closure func()
closure = func() {
fmt.Println("Calling recursively")
closure()
}
closure()
}
Program 3:
package main
import "fmt"
func main() {
var num = 0
var closure func()
closure = func() {
num = num + 1
fmt.Println("Calling recursively")
if num == 5 {
return
}
closure()
}
closure()
}
Program 4:
package main
import "fmt"
var num = 0
var closure func()
func main() {
closure = func() {
num = num + 1
fmt.Println("Calling recursively")
if num == 5 {
return
}
closure()
}
closure()
}
Program 5:
package main
import "fmt"
func sayHello() {
fmt.Println("Hello World")
}
func main() {
var ptr *func()
ptr()
}
Answer Program 1:
Output:
Explanation:
The above program will generate a syntax error because we cannot use a func() keyword like this.
Answer Program 2:
Output:
Explanation:
In the above program, we implemented a recursive closure function and printed the "Calling recursively" message infinite times.
Answer Program 3:
Output:
Explanation:
In the above program, we implemented a recursive closure function and printed the "Calling recursively" message 5 times.
Answer Program 4:
Output:
Explanation:
In the above program, we declared variable num and closure function globally. Then we implemented the recursive closure function inside the main() function and printed the "Calling recursively" message 5 times.
Answer Program 5:
Output:
Explanation:
The above program will generate a syntax error because we cannot non-function the pointer.
need an explanation for this answer? contact us directly to get an explanation for this answer