Best way to declare/initialize Global variables during application initialization

Hi guys,

Had the following doubt while thinking of adding a init() func to main.go (to define scalar types available globally):

Not sure if we already do this kind of thing, if we do, please point me to it.

  • Suppose we want to declare global vars (similar to postingDir, uidDir declared in main.go) but we also want to do error handling with them.
  • We don’t want to declare them in main.go (don’t want to clutter it), but initialize them before it’s execution starts.
  • We want to define those variables in the package where their parent type/struct is defined.

What would be the best way to do this?

My proposal:

  1. Maintain a init() method in main.go
  2. Declare required global vars in the intended package
  3. Define those vars in a func inside that file
  4. Handle errors
  5. Call this function from init() inside main.go

Would love to hear everyone’s thoughts on this.

Each module has it’s own init() function that you can use. It gets called automatically during module initialization.

Here is my take. I’m very open to suggestions. In my latest PR, I am trying to emulate this “GoogleInit” function. Here is roughly how it works.

There are two rounds of initialization. First round is the package init. Things are not fully initialized yet, so you want to be more careful with what you do here. For example, flags are not ready. But what you can do is to call x.AddInit(func() {…}). Then in every main, we would call x.Init at the very start to (1) initialize flags, then (2) run all the functions added by x.AddInit. In the second round of init, the flag values are ready, so you can now initialize all those global vars.

1 Like

This way is much cleaner. Especially, if you want to use global flags in
your init() function.
For now, will update my PR to use normal init() sequence.
But we should probably follow your method globally to ensure a strictly
well-defined initialization.

Thanks @akhiltak. I am afraid that PR might take a while to go in. If you like, I can factor that part into another PR first?

That would be awesome @jchiu if possible. Or I could do these changes as part of my PR and you could review those before I merge. Let me know what works for you.

Yes, let me send out a PR. It should be really short.

Add: Hi @akhiltak, I just pushed the change. Please see x/init.go. Thanks!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.