Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I am watching the keynote, it looks interesting. I don't know Go at all, though I know several languages including C.

I don't quite know what he is talking about when he talks about main and initialization. Can anyone elaborate on this for me?

I hate to say this because I feel like a jerk in doing so, but I'm about 25 minutes in and the little gopher that scrolls across the screen (some sort of advertisement, I think) is so distracting. It is awful.



Function main() in package "main" is the entry point for a Go application but it is not the first code that gets executed when you start a Go app. Each package can have an init() function which gets executed in the order of dependency (if pkg A imports pkg B then B.init() is executed before A.init()) before main.main() is executed.


It's slightly more complicated than that: In addition to the init() function, variables on the package level can be initialized during initialization too.

For example: http://play.golang.org/p/tvlX7cqaaB

This is important for package level variables such as arrays. Since there are only a very limited number of types which can be constants in Go, everything else which you'd use like a constant needs to be initialized.


If we go in details, we can also add that goroutines created in init() or at init time are effectively started only after all init() functions finish.


I see. Thank you.


Not a Go expert, but I think it has to do with global variables/constants in modules. In C, what can run before main() is extremely limited. In C++, much more can happen before main(), i.e. running constructors for static objects, and the initialization order is undefined (this is a pretty well known problem).

I guess in Go you can also have relatively elaborate static initialization, so it has a similar problem as C++? Interested if any Go users can elaborate on this.


Like in the Object Pascal/Modula-2 language family, you can define a package initialization sections.

There are executed before control reaches main, and you need to have import relationships into consideration.


The gophers are being removed by popular demand.


Nice!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: