go - golang 中的 map[T]struct{} 和 map[T]bool

标签 go

有什么区别? 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/

相关文章:

go - 为什么要使用简写语法来声明/初始化变量?

go - SETEX 错​​误 - "Use of closed network connection"

mongodb - 过滤集合但按内部属性排序

go - 如何创建一个字符串数组并从[] net.ip追加数据

postgresql - 如何将 pgx.Rows 从 Query() 转换为 json 数组?

curl - 如何在 Go 中设置空授权 header ?

methods - 使用函数名作为参数

json - 在 Golang 中解析 JSON 数据

go - "bad quoted string"在生成

Golang unicode 字符值