我在 Go 中使用 map 映射[键]接口(interface){}
所以我在 Map 中的键值对看起来像 -
map[
1:{12234 145 1000}
1234:{1234 15 1000}
12:{12 12345 1000}]
其中 1 是键,{12234,145,1000} 是对应于该键的值
这是 struct,它是 map 中的值图像
type AddStruct struct {
AdID int
Category int
Impression int
}
type Handler struct {
Conmap cmap.ConcurrentMap
}
我在 Go 中使用并发映射 这就是我向映射添加键值对的方式
func (h *Handler) Add(input AddStruct){
AdID := strconv.Itoa(input.AdID)
h.Conmap.Set(AdID,input)
}
但是我在访问它们时面临的问题是 我需要从映射中返回所有具有在函数参数中指定的相同类别的键值对
func(h *Handler) Fetch(category int) []int {
h.Conmap.IterCb(func(key string, v interface{}) {
fmt.Printf("%s\n", key) //1
fmt.Printf("%v\n",v.(AddStruct)) // {12234 145 1000}
I only need 145 to here to check! Or how do i access 145 here ?
})
}
那么我如何访问值接口(interface)中的每个值呢??
最佳答案
v.(AddStruct).Category
在有效的类型断言之后,您可以使用断言类型的有效选择器访问结构字段。参见,例如,这个可运行的例子:
package main
import(
"fmt"
)
type AddStruct struct {
AdID int
Category int
Impression int
}
func main() {
a := AddStruct{12234, 145, 1000}
var b interface{}
b = a
fmt.Printf("%v\n", b.(AddStruct).Category)
}
打印145
关于go - 在 Go 中访问 map 接口(interface)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612306/