当struct在Slice中时访问Struct

时间:2016-05-03 15:16:55

标签: go

我需要从下面的结构中生成一个Form。我需要访问每个字段并在Doc上键入以生成表单。我的问题是当它们在切片上时访问结构域。

这是代码

package main

import (
    "fmt"
    "net/url"
    "time"
    "reflect"
    "strings"
    "strconv"

)
type TestStruct struct {

    Children22 struct {// I can acess this one ( see code) 
            ID   string
            Name string
        }
    Children23 []struct { // this is not struct it is slice of sruct
            ID1   string    // I would like to access this one
            Name1 string
        }
    Nest struct {
        Children []struct {  // I would like to get to this one too
            ID2   string
            Name2 string
        }
    }
}

func main() {

    var t1 TestStruct
    t1.InterfaceStruct = &InterfaceStruct{}
    main := reflect.ValueOf(&t1)
    err := GetField(main)
            if err != nil {
                fmt.Println("Error lev 1 = ", err)
            }
    }

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) // recall the func to get the struct
                if err != nil {
                    fmt.Println("Error = ", err)
                }
            }
        }
        if elemKind  ==  reflect.Map {
            fmt.Println("is a Map")
        }

    fmt.Println(" ")

    }
    return nil
}

0 个答案:

没有答案