简体   繁体   English

如何获取go struct的字段

[英]How to get the fields of go struct

Lets say we have a User type 让我们说我们有一个User类型

type User struct {
    FirstName string
    LastName  string
    ...
}

I need a function that returns []string with the field names in it [FirstName, LastName, ...] 我需要一个函数返回[]string其中包含字段名称[FirstName, LastName, ...]

This can be done using reflection (via the reflect package): 这可以使用反射(通过反射包)完成:

instance := struct{Foo string; Bar int }{"foo", 2}

v := reflect.ValueOf(instance)

names := make([]string, 0, v.NumField())

v.FieldByNameFunc(func(fieldName string) bool{
    names = append(names, fieldName)
    return false
})

Live example on play . 游戏中的实例。

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

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