×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang Closures | Find Output Programs | Set 2

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

Program 1:

package main

import "fmt"

func main() {  
    var num=0

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

    counter()
}

Output:

./prog.go:14:11: type func() is not an expression

Explanation:

The above program will generate a syntax error because we cannot use a func() keyword like this.


Program 2:

package main

import "fmt"

func main() {
	var closure func()
	
	closure = func() {
		fmt.Println("Calling recursively")
		closure()
	}
	
	closure()
}

Output:

Calling recursively
Calling recursively
Calling recursively
Calling recursively
Calling recursively
Calling recursively
Calling recursively
Calling recursively
Calling recursively
....
....
Infinite times

Explanation:

In the above program, we implemented a recursive closure function and printed the "Calling recursively" message infinite times.


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()
}

Output:

Calling recursively
Calling recursively
Calling recursively
Calling recursively
Calling recursively

Explanation:

In the above program, we implemented a recursive closure function and printed the "Calling recursively" message 5 times.


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()
}

Output:

Calling recursively
Calling recursively
Calling recursively
Calling recursively
Calling recursively

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.


Program 5:

package main

import "fmt"

func sayHello() {
	fmt.Println("Hello World")
}

func main() {
	var ptr *func()
	ptr()
}

Output:

./prog.go:11:5: cannot call non-function ptr (type *func())

Explanation:

The above program will generate a syntax error because we cannot non-function the pointer.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





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