Get all fields from the interface

How to find out the fields that I can get from an object / interface reply? I tried to speculate, but it seems like you need to know the name of the field first. What should I do if I need to know all the fields available to me?

// Do sends a command to the server and returns the received reply.
Do(commandName string, args ...interface{}) (reply interface{}, err error)
+4
source share
1 answer

You can use the function reflect.TypeOf()to get reflect.Type. From there, you can specify the dynamic value fields stored in the interface.

Example:

type Point struct {
    X int
    Y int
}

var reply interface{} = Point{1, 2}
t := reflect.TypeOf(reply)
for i := 0; i < t.NumField(); i++ {
    fmt.Printf("%+v\n", t.Field(i))
}

Conclusion:

{Name:X PkgPath: Type:int Tag: Offset:0 Index:[0] Anonymous:false}
{Name:Y PkgPath: Type:int Tag: Offset:4 Index:[1] Anonymous:false}

The result of the call Type.Field()is a reflect.StructFieldvalue structcontaining the name of the field among other things:

type StructField struct {
    // Name is the field name.
    Name string
    // ...
}

, reflect.ValueOf(), reflect.Value(), Value.Field() Value.FieldByName():

v := reflect.ValueOf(reply)
for i := 0; i < v.NumField(); i++ {
    fmt.Println(v.Field(i))
}

:

1
2

Go Playground.

. . Type.Elem() Value.Elem() :

t := reflect.TypeOf(reply).Elem()

v := reflect.ValueOf(reply).Elem()

, , Type.Kind() Value.Kind(), reflect.Ptr:

t := reflect.TypeOf(reply)
if t.Kind() == reflect.Ptr {
    t = t.Elem()
}

// ...

v := reflect.ValueOf(reply)
if v.Kind() == reflect.Ptr {
    v = v.Elem()
}

Go Playground.

Go : .

+13

Source: https://habr.com/ru/post/1656762/


All Articles