On Thursday, 24 March 2022 at 11:30:37 UTC tapi...@gmail.com wrote: > > 2. A < D < B < C - happens when f2.go is passed first to the compiler. > In this case, the *expected output *would be "1 2 1". However, the *actual > output* is "1 2 3". > > This is not true by my understanding of the spec. > https://go.dev/ref/spec#Package_initialization >
The spec says: *"Initialization proceeds by repeatedly initializing the next package-level variable that is earliest in declaration order and ready for initialization, until there are no variables ready for initialization.* *If any variables are still uninitialized when this process ends, those variables are part of one or more initialization cycles, and the program is not valid."* This hinges on how you read "next", but my reading is that you keep jumping back to the start of the list, to find the variable "*earliest* in declaration order" which is ready for initialization. I think your interpretation is that "next" means you move to the next variable lexically *after* the one you've just initialized which is now ready - not the earliest one. By that reading you have to cycle round and round until there are no more changes (which would involve keeping a flag to remember whether anything changed during a given cycle). I don't think that's what it says. By my reading, and given the lexical order is D < A < B < C: 1. D is not ready (because it depends on A) 2. A is ready, so it is initialized: it gets value 3. 3. Now D is the earliest variable which is ready, so D is initialized. It gets value 1, and A is set to 1. 4. B is initialized. It gets value 2 5. C is initialized. It gets value 1 We got to the end and everything is initialized, success. Result is 1 2 1. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/f1d83953-9081-4325-843b-cf9e4fa8cfb2n%40googlegroups.com.