0
votes

I have a struct:

 type ListsObj struct {
    Page   string                   `json:"pages"`
    Count  string                   `json:"count"`
    Lists []map[string]interface{} `json:"assets"`
}

I am trying to do something like below:

lists := a.Lists
for _, list:= range lists{
    listData := list.(map[string]interface {})
}

a is of type ListsObj struct.

I am getting following error:

invalid type assertion: list.(map[string]) (non-interface type map[string]interface {} on left)

EDIT: What I actually need to do is to call a function:

func WriteMapper(a interface {}) interface{}  {

}

lists := a.Lists
for _, list:= range lists{
    list = WriteMapper(list)
}

but this gives another error:

cannot use WriteMapper(list) (type interface {}) as type map[string]interface {} in assignment: needs type assertion

EDIT: I think I got it... the function returns interface and I am trying to assign that to map[string]interface {}??

1

1 Answers

1
votes

In your code, a.Lists (and therefore also lists) is a []map[string]interface{}, a slice of maps. You're then iterating over that slice, and assigning the value on each iteration to the variable list (which is kinda oddly named, as it's holding a map, but that's a separate concern).

Now, list is of type map[string]interface{}. There's no need for you to type-assert it into that, since it's already that type!

To use list as the map[string]interface{} that it is, you just use it:

for _, list := range lists {
    someValue := list["some-key"]
    fmt.Println(someValue)
}

If you're trying to do something different that just using the map, I'd ask that you please clarify.