Reputation: 3480
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
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