0
votes

I am getting compilation error while declaring anonymous function outside main() block. I am curious about the scope of anonymous function in go. Assigning to a variable works but without assignment it does not work. What is the difference between both the piece of codes ???

This code does not work !! `

package main
import "fmt"

func(){
      fmt.Println("Welcome! from Anonymous function")
}

func main() {
        printme := ()
}

` This piece of code works !!

`

package main
import "fmt"

var pri = func(){
      fmt.Println("Welcome! from Anonymous function")
}

func main() {

        pri()
}

` Error it gives for the not working portion is:

command-line-arguments

./anony-func-2.go:8:7: syntax error: unexpected {, expecting name or ( ./anony-func-2.go:8:8: method has no receiver ./anony-func-2.go:14:14: syntax error: unexpected ), expecting expression

1

1 Answers

0
votes

Quoting from this blog:

The main() function is a special type of function and it is the entry point of the executable programs. It does not take any argument nor return anything. Go automatically call main() function, so there is no need to call main() function explicitly and every executable program must contain single main package and main() function.

Which means that no other function except the main() function will be invoked, so it makes no sense to have an anonymous function outside main() since it will not be called anyways.