I have a config object which initializes some variables based on environment variables at startup:
// init the conf object on startup and fail quickly if there's an environment issue
_ = utils.GetConf()
This is in the init() method of my server, and in other places in my code, I just call GetConf() to get the config object. I'd like to implement this config object through a singleton pattern:
import (
"fmt"
env "github.com/Netflix/go-env"
)
type Conf struct {
DBName string `env:"MONGO_INITDB_DATABASE,required=true"`
Hostname string `env:"HOSTNAME,required=true"`
DBUsername string `env:"MONGO_INITDB_ROOT_USERNAME,required=true"`
DBPassword string `env:"MONGO_INITDB_ROOT_PASSWORD,required=true"`
}
var gConf *Conf
func GetConf() *Conf {
if gConf != nil {
return gConf
}
gConf = new(Conf)
_, err := env.UnmarshalFromEnviron(gConf)
if err != nil {
panic(err)
}
return gConf
}
Since I'm not doing anything with the return value of utils.GetConf() at the start, is it possible that golang will garbage collect my config object and my gConf pointer will end up pointing to nowhere?
CodePudding user response:
If you create a pointer to a value, dereferencing that pointer will yield that value.
That is really all you must bear in mind. The garbage collection system may be doing whatever it's doing behind the scene, but the above statement must still remain true. If the garbage collector were to invalidate your pointers before you use them, that would be a broken implementation of the language (i.e., a compiler bug).
When in doubt about how Go works, always consult the Go language specification. You'll see that pointer behaviour is plainly defined. Garbage collection, on the other hand, is only mentioned in the introduction without defining any behaviour. Therefore, we can assume that garbage collection should not override or otherwise interfere with the way pointers are supposed to work.
CodePudding user response:
Your variable gConf
is a package global variable (and not visible for other packages).
A global variable refers to a variable that is defined outside a function.
Global variables hold their value throughout the program’s lifetime.
If you change de value a
referenced by gConf
for a value b
in any part of the code, and value a
remains dereferenced, then the dereferenced value a
will be garbage collected, but not b
(referenced by gConf
).
So in short for your question: No, unless you explicitly change it.