'How can I declare a struct of maps as a global variable?
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.
Solution 1:[1]
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{},
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RedBlue |
