How can I declare a struct of maps as a global variable?

Issue

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

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{},
}

Answered By – Zombo

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.