Go中的地图类型强制是否可行?我想做的是:
type IDMap map[string]bool
type ObjectMap map[string]Object
然后编写带有类型map[string]interface{}
的参数的函数,以便我可以将这些基类型中的任何一个作为参数处理,如下所示:
func (im IDMap) Intersect(other map[string]interface{}) {
result = make(IDMap, 0)
for k := range im {
if _, ok := other[k]; ok {
result[k] = true
}
}
return result
}
func (om ObjectMap) Intersect(other map[string]interface{}) {
result = make(ObjectMap, 0)
for k := range om {
if _, ok := other[k]; ok {
result[k] = om[k]
}
}
return result
}
允许我使用任一类型的对象调用任一类型的Intersect方法。当我尝试时,我收到一个类型错误消息。这样的事情可能吗?
答案 0 :(得分:0)
尝试使用interface{}
和switch
类型检查:
package main
import (
"fmt"
)
type IDMap map[string]bool
type ObjectMap map[string]interface{}
type Map interface {
Intersect(interface{}) Map
}
func main() {
im1 := IDMap{"a": true, "b": false, "c": true, "e": false}
other1 := IDMap{"b": true, "d": false, "e": true}
other2 := ObjectMap{"b": false, "x": 1, "y": 3.4, "z": "hello"}
other3 := map[string]interface{}{"m": 5.4, "n": false, "o": "world", "b": "foo", "a": "bar"}
overlap1 := im1.Intersect(other1)
check(overlap1)
overlap2 := im1.Intersect(other2)
check(overlap2)
overlap3 := im1.Intersect(other3)
check(overlap3)
im2 := ObjectMap{"a": "hello", "b": 4.5, "c": 10, "e": []string{"what?"}}
other4 := IDMap{"b": true, "d": false, "e": true}
other5 := ObjectMap{"b": false, "x": 1, "y": 3.4, "z": "hello"}
other6 := map[string]interface{}{"m": 5.4, "n": false, "o": "world", "b": "foo", "a": "bar"}
overlap4 := im2.Intersect(other4)
check(overlap4)
overlap5 := im2.Intersect(other5)
check(overlap5)
overlap6 := im2.Intersect(other6)
check(overlap6)
}
func check(m Map) {
fmt.Println(m)
}
func (im IDMap) Intersect(other interface{}) Map {
result := IDMap{}
switch o := other.(type) {
case IDMap:
for k := range im {
if _, ok := o[k]; ok {
result[k] = true
}
}
case ObjectMap:
for k := range im {
if _, ok := o[k]; ok {
result[k] = true
}
}
case map[string]interface{}:
for k := range im {
if _, ok := o[k]; ok {
result[k] = true
}
}
}
return result
}
func (om ObjectMap) Intersect(other interface{}) Map {
result := ObjectMap{}
switch o := other.(type) {
case IDMap:
for k := range om {
if _, ok := o[k]; ok {
result[k] = om[k]
}
}
case ObjectMap:
for k := range om {
if _, ok := o[k]; ok {
result[k] = om[k]
}
}
case map[string]interface{}:
for k := range om {
if _, ok := o[k]; ok {
result[k] = om[k]
}
}
}
return result
}