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 中添加元素。
以上就是Go 语言结构体 map 字段如何避免初始化时的 panic 错误?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号