go - 在 Go 中访问 map 接口(interface)值

标签 go

我在 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/

相关文章:

go - Go 中的类型变量

mysql - MySQL release_lock()是否阻塞?

go - 从嵌套映射类型获取值 map[string]interface{}

go - 我如何绕过没有参数多态性的 Go?

go - 为什么我得到一个引用接口(interface)的空变量?

go - 将 slice 扩展到其容量的最简单方法是什么?

go - 使用 GORM golang 持久化自定义集数据类型

go - golang中是否有一个虚拟指针类型作为函数参数

go - 运行时错误 : Index out of range when attempting to os. StartProcess

mongodb - mgo 中的 Golang 和 mongodb 查询