例如我有这样一个结构体
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 赋值时自动初始化?
go 的一般做法是定义一个 NewTrie: