Function declaration in Golang

function, go

Solution

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.

Problem

It seems there are two different ways to declare a function in Golang, like this: ``` package main import "fmt" var someFunc = func(arg string) { fmt.Println(arg) } func main() { someFunc("Hello") } ``` The above works. However, the below does not work: ``` package main import "fmt" var someFunc = func(arg string) { fmt.Println(arg) } var main = func() { someFunc("Hello") } ``` It will complain: ``` runtime.main: undefined: main.main ``` So what's the difference between `func someFunc()` and `var someFunc = func()`? The reason I found this is probably because of I code a lot of Javascript, too. It seems in Go, I rarely see people declaring a function like `var someFunc=func()`. Of these two, can we say which one is more correct than the other one?

Original source