0
votes

I am using Maps in Go like Map[Key]interface{}

so my key-value pair inside Map looks like -

map[
 1:{12234 145 1000} 
    1234:{1234 15 1000} 
    12:{12 12345 1000}]

where 1 is the key and {12234,145,1000} is the value corresponds to that key

And this is struct which is a image of value inside the map

 type AddStruct struct {
    AdID         int
    Category     int
    Impression   int
 }

    type Handler struct {
    Conmap cmap.ConcurrentMap 
   }

I am using concurrent maps in Go This is how i am adding key-value pair to maps

   func  (h *Handler) Add(input AddStruct){
       AdID := strconv.Itoa(input.AdID)
       h.Conmap.Set(AdID,input)
    }

But the problem that I am facing in accessing them is I need to return all the key value pairs from the map which are having same category specified in function argument

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 ?


})
}

So how do i access each value inside the value interface??

1

1 Answers

4
votes
v.(AddStruct).Category

After a valid type assertion, you can access struct fields with a valid selector for the asserted type. See, e.g., this runnable example:

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)
}

prints 145