GO 语言结构体里定义 map 字段,使用时如何自动初始化?

例如我有这样一个结构体

type Trie struct {
    isEnd    bool
    children map[rune]*Trie
}

当我初始化一个 Trie 变量,当他的某个 child 为空时为它赋值时会报错 panic: assignment to entry in nil map

root := Trie{}
    
if root.children['a'] == nil {
    root.children['a'] = &Trie{}
}

对于这种情况,难道我每次赋值前都要先检查 map 是否被初始化了吗?如下:

root := Trie{}
    
if len(root.children) == 0 {
    root.children = map[rune]*Trie{}
}
    
if root.children['a'] == nil {
    root.children['a'] = &Trie{}
}

有没有更优雅的语法或做法,让为结构体的 map 赋值时自动初始化?

阅读 1.5k
1 个回答

go 的一般做法是定义一个 NewTrie:

func NewTrie() *Trie {
    return &Trie{
        true,
        map[rune]*Trie{}
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题