Oguz Bilgic
Oguz Bilgic

Reputation: 3480

How to get the fields of go struct

Lets say we have a User type

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

I need a function that returns []string with the field names in it [FirstName, LastName, ...]

Upvotes: 3

Views: 188

Answers (1)

nemo
nemo

Reputation: 57639

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.

Upvotes: 4

Related Questions