How reflect an slice of struct

44 views
Skip to first unread message

luis...@gmail.com

unread,
May 2, 2016, 9:45:16 PM5/2/16
to golang-nuts
Hi I am new at GO I will appreciate your help.
I need to access the name an type using reflect of the following type

type TestStruct struct {
 Children22 struct {               // this one is OK see code below
                ID22       string
                Name22 string
  }
 Children23 []struct {    // This is the one I want to get
   ID   string
   Name string
  }

 Nest struct {              // this one also
      Children []struct {
                             ID   string
                           Name string
  }
 
this is my code
func main() {
 var t1 TestStruct
 t1.InterfaceStruct = &InterfaceStruct{}
   }
func GetField ( f reflect.Value ) error {
     
 if f.Kind() != reflect.Ptr {
  fmt.Println("Error not a pointer  ") 
 }
 val := f.Elem()
 lenght := val.NumField()
 for i := 0; i < lenght; i++ {
  typefield := val.Type().Field(i)
  elementType := val.Type().Field(i).Type
  type_filed := val.Type().Field(i).Type.String()
  elemKind    := elementType.Kind()
  
  fmt.Println("typefield.Name = ", typefield.Name)
  fmt.Println("elementType    = ", elementType)
  fmt.Println("what kind =", elemKind )
  
  if elemKind  ==  reflect.Slice{
   fmt.Println("is a Slice")
   fmt.Println(" Slice type =", val.Field(i).Addr().Elem().Type() )
   // what kind of slice
   if strings.Contains(type_filed ,"struct") {
   
    // I do not know how to address the struct inside the slice
    
   }
  }
  if elemKind  == reflect.Struct {  // check first for time and URL are Struct
   if type_filed != "time.Time" && type_filed != "url.URL" {
   fmt.Println("is a struct ")
    //pass this to function recursive as   reflect.Value
   newSt := val.Field(i).Addr() // this works fine
   err := GetField(newSt)
    if err != nil {
     fmt.Println("Error = ", err)
    }
   }
  }
  if elemKind  ==  reflect.Map {
   fmt.Println("is a Map")
  }
 
 fmt.Println(" ")
 
 }
 return nil
}

Thanks in advance.

Luis


Reply all
Reply to author
Forward
0 new messages