英文:
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
}
但是usersMap
和entriesMap
不是类型。
如果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{},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论