dictionary - Convert interface{} to map in Golang -


i trying create function accept following

*struct []*struct map[string]*struct 

here struct struct not specific one. converting interface *struct or []*struct working fine. giving error map.

after reflect shows map[] giving error when try iterate on range.

here code

package main  import (     "fmt"     "reflect" )  type book struct {     id     int     title  string     year   int }  func process(in interface{}, isslice bool, ismap bool) {     v := reflect.valueof(in)      if isslice {         := 0; < v.len(); i++ {             strct := v.index(i).interface()             //... proccess struct         }         return     }      if ismap {         fmt.printf("type: %v\n", v)     // map[]         _, s := range v {           // error: cannot range on v (type reflect.value)             fmt.printf("value: %v\n", s.interface())         }     }     }  func main() {     b := book{}     b.title = "learn go language"     b.year = 2014     m := make(map[string]*book)     m["1"] = &b      process(m, false, true) } 

is there way convert interface{} map , iterate or it's elements.

if map value can type, use reflect iterate through map:

if v.kind() == reflect.map {     _, key := range v.mapkeys() {         strct := v.mapindex(key)         fmt.println(key.interface(), strct.interface())     } } 

playground example

if there's small , known set of struct types, type switch can used:

func process(in interface{}) {   switch v := in.(type) {   case map[string]*book:      s, b := range v {          // b has type *book          fmt.printf("%s: book=%v\n" s, b)      }   case map[string]*author:      s, := range v {          // has type *author          fmt.printf("%s: author=%v\n" s, a)      }    case []*book:      i, b := range v {          fmt.printf("%d: book=%v\n" i, b)      }    case []*author:      i, := range v {          fmt.printf("%d: author=%v\n" i, a)      }    case *book:      fmt.ptintf("book=%v\n", v)    case *author:      fmt.printf("author=%v\n", v)    default:      // handle unknown type    } } 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -