首页 > 解决方案 > 使用带有空接口的地图作为 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{}
}

第二个选项效果很好(你可以在这里找到我的完整代码),但我担心我忽略了一些明显的东西,以后会遇到问题。

谢谢你的帮助。

标签: gohashmapgo-interfacego-map

解决方案


推荐阅读