I also had need for something like this. I was using an internal package which was converting a struct to a map. I decided to open source it with other struct
based high level functions. Have a look:
https://github.com/fatih/structs
It has support for:
- Convert struct to a map
- Extract the fields of a struct to a
[]string
- Extract the values of a struct to a
[]values
- Check if a struct is initialized or not
- Check if a passed interface is a struct or a pointer to struct
You can see some examples here: http://godoc.org/github.com/fatih/structs#pkg-examples For example converting a struct to a map is a simple:
type Server struct {
Name string
ID int32
Enabled bool
}
s := &Server{
Name: "gopher",
ID: 123456,
Enabled: true,
}
// => {"Name":"gopher", "ID":123456, "Enabled":true}
m := structs.Map(s)
The structs
package has support for anonymous (embedded) fields and nested structs. The package provides to filter certain fields via field tags.