简体   繁体   English

从界面获取所有字段

[英]Get all fields from an interface

How do I know the fields I can access from the reply object/interface? 如何知道我可以从reply对象/界面访问的字段? I tried reflection but it seems you have to know the field name first. 我尝试过反射,但似乎你必须首先知道字段名称。 What 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)

You can use the reflect.TypeOf() function to obtain a reflect.Type type descriptor. 您可以使用reflect.TypeOf()函数来获取reflect.Type类型描述符。 From there, you can list fields of the dynamic value 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))
}

Output: 输出:

{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 a Type.Field() call is a reflect.StructField value which is a struct , containing the name of the field among other things: Type.Field()调用的结果是一个reflect.StructField值,它是一个struct ,包含字段的名称以及其他内容:

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

If you also want the values of the fields, you may use reflect.ValueOf() to obtain a reflect.Value() , and then you may use Value.Field() or Value.FieldByName() : 如果您还想要字段的值,可以使用reflect.ValueOf()来获取reflect.Value() ,然后您可以使用Value.Field()Value.FieldByName()

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

Output: 输出:

1
2

Try it on the Go Playground . Go Playground尝试一下。

Note: often a pointer to struct is wrapped in an interface. 注意:通常指向struct的指针包含在接口中。 In such cases you may use Type.Elem() and Value.Elem() to "navigate" to the pointed type or value: 在这种情况下,您可以使用Type.Elem()Value.Elem()来“导航”到指向的类型或值:

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

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

If you don't know whether it's a pointer or not, you can check it with Type.Kind() and Value.Kind() , comparing the result with reflect.Ptr : 如果您不知道它是否是指针,可以使用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()
}

Try this variant on the Go Playground . Go Playground上试试这个变种。

For a detailed introduction to Go's reflection, read the blog post: The Laws of Reflection . 有关Go的反思的详细介绍,请阅读博客文章: 反思的法则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM