go - 使用带有空接口的地图作为 KEY 是否存在任何编程缺陷
问题描述
以这种方式使用地图是否有任何编程缺陷:
type Set struct {
theMap map[interface{}]struct{}
}
StringSet := NewSet("abc", "pqr")
IntSet := NewSet(1, 2)
DateSet := NewSet(time.Date(2021, 2, 15, 0, 0, 0, 0, time.UTC))
为了清楚起见,我知道我正在做的事情可能违背了几个“最佳实践”的精神,但这不是我的问题。我特别考虑编程问题,例如由于元素大小不同导致的内存问题、哈希冲突的机会增加、由于类型断言增加导致的性能下降等。
更多信息:我需要在我的应用程序中创建一些各种数据类型的“集合”。我在 Essential Go 中看到使用集合的最佳方法是使用带有空结构的映射作为值。
但是,在没有泛型的情况下,我要么需要为我希望存储在我的集合中的每种数据/元素类型创建一种新类型的 Set:
type StringSet struct {
stringMap map[string]struct{}
}
type DateSet struct {
dateMap map[time.Time]struct{}
}
type IntSet struct {
intMap map[int]struct{}
}
...或者,使用空接口作为 hashmap 的键:
type Set struct {
theMap map[interface{}]struct{}
}
第二个选项效果很好(你可以在这里找到我的完整代码),但我担心我忽略了一些明显的东西,以后会遇到问题。
谢谢你的帮助。
解决方案
推荐阅读
- makefile - Makefile.inc 不存在 plexe-veins
- javascript - BrowserSync 与 Gulp 在更改完成之前重新加载浏览器
- sql - Oracle 不返回正确的日期类型值。(使用解码功能)
- java - jedis是否无法从从节点获得连接?
- c# - C# ConsoleWriteLine,ReadLine 错误?
- java - 通过外部类的内部类实例访问外部类字段
- java - hikariCP 中的借用测试配置
- apache - Apache2 Proxy 路由错误
- unity3d - 调整屏幕大小会影响 Unity 中的触发器
- javascript - 搜索键名的开头并重命名