In order to declare a global map, I can directly initialize it at creation time:
package main
var a = map[string]string{}
func main() {
a["hello"] = "world"
}
How can I initialize a global struct of maps? A similar approach is incorrect:
var db struct {
Users map[string]User{}
Entries map[string]Entry{}
}
I also tried something like
var usersMap = map[string]User{}
var entriesMap = map[string]Entry{}
var db struct {
Users usersMap
Entries entriesMap
}
but usersMap
and entriesMap
are not types.
I would be fine to initialize db
from within main()
, provided that it is still global.
CodePudding user response:
A struct field declaration expects a type, not a value. The composite literal expressions map[string]User{}
and map[string]Entry{}
are values, not types.
Fix by separating the field type declarations from the field value initializations:
var db = struct {
Users map[string]User
Entries map[string]Entry
}{
Users: map[string]User{},
Entries: map[string]Entry{},
}
CodePudding user response:
You can create a constructor method for the struct like so --
var db struct {
Users map[string]User{}
Entries map[string]Entry{}
}
func NewDB() Foo {
return &db{
Users: make(map[string]User{}),
Entries: make(map[string]Entry{}),
}
}
Then call the NewDB function whenever you need to create a db
object.
If you want to craete a singleton object you could make use of sync.once
module. https://pkg.go.dev/sync#Once.
The singleton object can be exposed via a public function. More on this here -- https://refactoring.guru/design-patterns/singleton/go/example