3 ms·
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 abo
by canadev 12y ago
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.
- leaveyou 12y agoFunction 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.
- canadev 12y agoI see. Thank you.
- Laremere 12y agoIt'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 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.
- leaveyou 12y agoIf 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.
- chubot 12y agoNot 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.
- pjmlp 12y agoLike 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.
- bketelsen 12y agoThe gophers are being removed by popular demand.
- canadev 12y agoNice!