Structs

Structs contains various utilities to work with Go (Golang) structs. It was
initially used by me to convert a struct into a map[string]interface{}
. With
time I've added other utilities for structs. It's basically a high level
package based on primitives from the reflect package. Feel free to add new
functions or improve the existing code.
Install
go get github.com/fatih/structs
Usage and Examples
Just like the standard lib strings
, bytes
and co packages, structs
has
many global functions to manipulate or organize your struct data. Lets define
and declare a struct:
type Server struct {
Name string `json:"name,omitempty"`
ID int
Enabled bool
users []string
http.Server
}
server := &Server{
Name: "gopher",
ID: 123456,
Enabled: true,
}
m := structs.Map(server)
v := structs.Values(server)
n := structs.Names(server)
f := structs.Fields(server)
n := structs.Name(server)
h := structs.HasZero(server)
z := structs.IsZero(server)
i := structs.IsStruct(server)
Struct methods
The structs functions can be also used as independent methods by creating a new
*structs.Struct
. This is handy if you want to have more control over the
structs (such as retrieving a single Field).
s := structs.New(server)
m := s.Map()
v := s.Values()
f := s.Fields()
n := s.Names()
f := s.Field(name)
f, ok := s.FieldOk(name)
n := s.Name()
h := s.HasZero()
z := s.IsZero()
Field methods
We can easily examine a single Field for more detail. Below you can see how we
get and interact with various field methods:
s := structs.New(server)
name := s.Field("Name")
value := name.Value().(string)
name.Set("another gopher")
name.Kind()
if name.IsExported() {
fmt.Println("Name field is exported")
}
if !name.IsZero() {
fmt.Println("Name is initialized")
}
if !name.IsEmbedded() {
fmt.Println("Name is not an embedded field")
}
tagValue := name.Tag("json")
Nested structs are supported too:
addrField := s.Field("Server").Field("Addr")
a := addrField.Value().(string)
httpServer := s.Field("Server").Fields()
We can also get a slice of Fields from the Struct type to iterate over all
fields. This is handy if you wish to examine all fields:
s := structs.New(server)
for _, f := range s.Fields() {
fmt.Printf("field name: %+v\n", f.Name())
if f.IsExported() {
fmt.Printf("value : %+v\n", f.Value())
fmt.Printf("is zero : %+v\n", f.IsZero())
}
}
Credits
License
The MIT License (MIT) - see LICENSE.md for more details