猿问

获取结构信息

该程序是:


    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)

    }


}

使用递归我想为请求获取相同的信息,这是结构的结构部分。


我需要作为参数传递什么?我尝试了各种方法,但我不得不认为这对我来说是很多试验和错误。


HUWWW
浏览 142回答 2
2回答

森林海

尝试这个:if&nbsp;varKind&nbsp;==&nbsp;reflect.Struct&nbsp;{ &nbsp;&nbsp;&nbsp;iterateStruct(e.Field(i).Interface())}e.Field(i)返回Value结构字段的 。Interface{}将返回基础值,因此您可以iterateStruct使用它调用。

慕桂英4014372

这是一个处理带有指向结构的指针的字段、包含结构值的接口等的示例。作为奖励,这个示例缩进了嵌套结构。func iterate(v reflect.Value, indent string) {&nbsp; &nbsp; v = reflect.Indirect(v)&nbsp; &nbsp; if v.Kind() != reflect.Struct {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; indent += "&nbsp; "&nbsp; &nbsp; for i := 0; i < v.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; varName := v.Type().Field(i).Name&nbsp; &nbsp; &nbsp; &nbsp; varKind := v.Field(i).Kind()&nbsp; &nbsp; &nbsp; &nbsp; varType := v.Type().Field(i).Type&nbsp; &nbsp; &nbsp; &nbsp; varValue := v.Field(i).Interface()&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s%v %v %v %v\n", indent, varName, varKind, varType, varValue)&nbsp; &nbsp; &nbsp; &nbsp; iterate(v.Field(i), indent)&nbsp; &nbsp; }}像这样称呼它:iterate(reflect.ValueOf(s), "")https://go.dev/play/p/y1CzbKAUvD_w
随时随地看视频慕课网APP

相关分类

Go
我要回答