gpt4 book ai didi

go - 在 Go 中强制映射类型

转载 作者:IT王子 更新时间:2023-10-29 02:23:16 24 4
gpt4 key购买 nike

在 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 方法。当我尝试时,我收到一条类型错误消息。这样的事情可能吗?

最佳答案

尝试使用 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
}

关于go - 在 Go 中强制映射类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com