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

WoJ

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.

Zombo

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive