Function declaration in Golang

When you do

var someFunc = func(arg string) {}

you are assigning an anonymous function to the somefunc variable. You could also write it like this:

somefunc := func(arg string) {}

The other way to create a function is to create a named function:

func somefunc(arg string) {}

Named functions can only be declared at the top level whereas anonymous functions can be declared anywhere. And main has a special meaning, there has to be a named function called main in the main package, that's why you got an error in the second case.


func main() {

This is declaring a function named main.

var main = func() {

This is declaring an anonymous function and assigning it to a variable called main. Functions are first-class data in Go. You can assign the function itself to a variable.


This is a function declaration:

func main() {}

This is a variable declaration:

var main = func() {}

The language specification says:

"The main package must have package name main and declare a function main that takes no arguments and returns no value."

A variable declaration isn't a function declaration and therefore doesn't meet the requirements for main.

Tags:

Function

Go