iterate over Interface

193 views
Skip to first unread message

Salim Aft

unread,
Dec 11, 2020, 10:20:21 AM12/11/20
to golang-nuts
Could someone help,
 I am trying to itreate over  an interface and fetch the "id" and "name" in below code,
is there a better way to do this.

package main

import (
    "fmt"
)

 type product struct {
     id int
     name string
 }
func main(){
    fmt.Println("Hello ALLTEST")
    p := product{id : 12, name:"apple"}
    c := product{id : 13, name:"samsung"}
    var pslice []product    
    pslice = append(pslice, p)
    pslice = append(pslice, c)
    d := map[string]interface{}{
        "allproducts" : pslice,
    }
    f:= d["allproducts"]
    fmt.Println("Output", f)

jake...@gmail.com

unread,
Dec 11, 2020, 11:25:25 AM12/11/20
to golang-nuts
I'm genuinely confused about what you are trying to accomplish. In the code you posted you don't iterate over anything. Also, the variables d and f in your code are completely redundant. You could remove the 4 lines and simply ` fmt.Println("Output", pslice )`, and get the same result. So, perhaps you could be more precise about what you have and what you want to do with it. For example, do you have an interface{} that you know contains a []product, and want to actually iterate over all the product items? or something else?
Reply all
Reply to author
Forward
0 new messages