
go 语言结构体 map 字段自动初始化
在 go 语言中,结构体的 map 字段在初始化时可能为空,导致对其进行操作时出现 panic 错误。例如,以下代码尝试向一个 trie 结构体的 children map 中添加一个新的元素:
type trie struct {
isend bool
children map[rune]*trie
}
root := trie{}
if root.children['a'] == nil {
root.children['a'] = &trie{}
}这将导致以下错误:
panic: assignment to entry in nil map
为了解决这个问题,可以在初始化结构体时明确初始化 map 字段。然而,这需要明确检查 map 是否为空,然后再对其进行初始化,如下所示:
root := trie{}
if len(root.children) == 0 {
root.children = map[rune]*trie{}
}
if root.children['a'] == nil {
root.children['a'] = &trie{}
}一种更优雅的做法是创建工厂函数,在创建结构体时自动初始化 map 字段。对于 trie 结构体,可以定义以下工厂函数:
func newtrie() *trie {
return &trie{
true,
map[rune]*trie{}
}
}然后,可以通过以下方式初始化 trie 结构体:
root := NewTrie()
这样,无需手动初始化 map 字段,即可向 children map 中添加元素。










