Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Obtain structure info

The program is:

    package main

import (
    "fmt"
    "reflect"
)

type Request struct {
    Method   string
    Resource string //path
    Protocol string
}

type s struct {
    ID        int
    Title     string
    Request   Request
    Price     float64
    Interface interface{}
    Exists    bool
    Many      []string
}

func main() {
    s := s{}    
    iterateStruct(s)
}

func iterateStruct(s interface{}) {

    e := reflect.ValueOf(s)

    for i := 0; i < e.NumField(); i++ {
        varName := e.Type().Field(i).Name
        varKind := e.Field(i).Kind()
        fmt.Println(e.Type().Field(i).Name)
        if varKind == reflect.Struct {
            //iterateStruct( <what should be here?>)
        }
        varType := e.Type().Field(i).Type
        varValue := e.Field(i).Interface()
        fmt.Printf("%v %v %v %v\n", varName, varKind, varType, varValue)
    }

}

Using recursion I’d like to get the same information for Request, that is a structure part of a structure.

What would I need to pass as a parameter? I tried various ways but I have to reckon it’s a lot of trial and error for me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

if varKind == reflect.Struct {
   iterateStruct(e.Field(i).Interface())
}

e.Field(i) returns the Value for the struct field. Interface{} will return the underlying value, so you can call iterateStruct using that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading