有什么区别? map[T]bool
是否针对 map[T]struct{}
进行了优化?哪个是 Go 中的最佳实践?
也许使用 map[T]struct{}
的最佳理由是您不必回答“如果值为 false 意味着什么
”这个问题>“?
最佳答案
来自“Go 编程语言”:
The struct type with no fields is called the empty struct, written
struct{}
. It has size zero and carries no information but may be useful nonetheless. Some Go programmers use it instead of bool as the value type of a map that represents a set, to emphasize that only the keys are significant, but the space saving is marginal and the syntax more cumbersome, so we generally avoid it.
如果您使用 bool
测试“集合”中的存在性会稍微好一些,因为您可以说:
if mySet["something"] {
/* .. */
}
关于go - golang 中的 map[T]struct{} 和 map[T]bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37320287/