如何将一个包含映射的结构声明为全局变量?

huangapple go评论92阅读模式
英文:

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

问题

为了声明一个全局的映射(map),我可以在创建时直接初始化它:

package main

var a = map[string]string{}

func main() {
    a["hello"] = "world"
}

如何初始化一个全局的映射结构体(struct of maps)呢?类似的方法是错误的:

var db struct {
    Users   map[string]User{}
    Entries map[string]Entry{}
}

我也尝试了以下方式:

var usersMap = map[string]User{}
var entriesMap = map[string]Entry{}

var db struct {
    Users   usersMap 
    Entries entriesMap 
}

但是usersMapentriesMap不是类型。

如果db仍然是全局的,我可以在main()函数内部初始化它。

英文:

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.

答案1

得分: 3

一个结构体字段声明需要一个类型,而不是一个值。复合字面表达式map[string]User{}map[string]Entry{}是值,而不是类型。

通过将字段类型声明与字段值初始化分开来修复:

var db = struct {
    Users   map[string]User
    Entries map[string]Entry
}{
    Users:   map[string]User{},
    Entries: map[string]Entry{},
}
英文:

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

huangapple
  • 本文由 发表于 2022年3月18日 03:35:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/71518103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定