Are you happy with your logging solution? Would you help us out by taking a 30-second survey? Click here

structs

Utilities for Go structs

Subscribe to updates I use structs


Statistics on structs

Number of watchers on Github 2007
Number of open issues 18
Average time to close an issue 9 days
Main language Go
Average time to merge a PR 4 days
Open pull requests 15+
Closed pull requests 13+
Last commit over 1 year ago
Repo Created about 5 years ago
Repo Last Updated over 1 year ago
Size 141 KB
Homepage http://godoc.org/...
Organization / Authorfatih
Latest Releasev1.0.0
Contributors9
Page Updated
Do you use structs? Leave a review!
View open issues (18)
View structs activity
View on github
Fresh, new opensource launches πŸš€πŸš€πŸš€
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating structs for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

Structs GoDoc Build Status Coverage Status

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 // not exported
    http.Server          // embedded
}

server := &Server{
    Name:    "gopher",
    ID:      123456,
    Enabled: true,
}
// Convert a struct to a map[string]interface{}
// => {"Name":"gopher", "ID":123456, "Enabled":true}
m := structs.Map(server)

// Convert the values of a struct to a []interface{}
// => ["gopher", 123456, true]
v := structs.Values(server)

// Convert the names of a struct to a []string
// (see "Names methods" for more info about fields)
n := structs.Names(server)

// Convert the values of a struct to a []*Field
// (see "Field methods" for more info about fields)
f := structs.Fields(server)

// Return the struct name => "Server"
n := structs.Name(server)

// Check if any field of a struct is initialized or not.
h := structs.HasZero(server)

// Check if all fields of a struct is initialized or not.
z := structs.IsZero(server)

// Check if server is a struct or a pointer to struct
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).

// Create a new struct type:
s := structs.New(server)

m := s.Map()              // Get a map[string]interface{}
v := s.Values()           // Get a []interface{}
f := s.Fields()           // Get a []*Field
n := s.Names()            // Get a []string
f := s.Field(name)        // Get a *Field based on the given field name
f, ok := s.FieldOk(name)  // Get a *Field based on the given field name
n := s.Name()             // Get the struct name
h := s.HasZero()          // Check if any field is initialized
z := s.IsZero()           // Check if all fields are initialized

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)

// Get the Field struct for the "Name" field
name := s.Field("Name")

// Get the underlying value,  value => "gopher"
value := name.Value().(string)

// Set the field's value
name.Set("another gopher")

// Get the field's kind, kind =>  "string"
name.Kind()

// Check if the field is exported or not
if name.IsExported() {
    fmt.Println("Name field is exported")
}

// Check if the value is a zero value, such as "" for string, 0 for int
if !name.IsZero() {
    fmt.Println("Name is initialized")
}

// Check if the field is an anonymous (embedded) field
if !name.IsEmbedded() {
    fmt.Println("Name is not an embedded field")
}

// Get the Field's tag value for tag name "json", tag value => "name,omitempty"
tagValue := name.Tag("json")

Nested structs are supported too:

addrField := s.Field("Server").Field("Addr")

// Get the value for addr
a := addrField.Value().(string)

// Or get all fields
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

structs open issues Ask a question     (View All Issues)
  • almost 3 years golang 1.7 issue
  • about 3 years Invalid Type
  • over 3 years Is there any option to create structs from map?
  • almost 4 years How to set a ptr field to nil
structs open pull requests (View All Pulls)
  • created flatnested tag to convert the anonymous field in a flat map
  • feat(MapPtr): returns a map with pointers to the struct fields
  • structs: add support for map and slice type
  • Value tag
  • Nest into struct for slice of pointer of struct
  • added dotflatten tag
  • update IsExported check for go1.6 refelct change
  • Really check if there are no exported fields instead of guessing usin…
  • incomplete suggestion for Mapper interface functionality
  • add flattenNames and customize tag omit filter
  • add "values" tag option
  • struct: add KeyFunc
  • Bring ability to override field name to Names()
  • Add hooks to allow struct value and type modification at encoding
  • Add `indirect` option
structs questions on Stackoverflow (View All Questions)
  • Learning Class and Structs
  • data types and structs in C#
  • archive array of optional structs with NSCoding in Swift?
  • Swig: Wrapping a vector of structs (nested in a class and namespace)
  • How do I choose between structs and classes for my MVC models?
  • structs in different headers refer to each other
  • How do I use switch with structs in C
  • C# getters/setters in structs and interfaces
  • Allocating Structs on Device
  • CUDA Array of Structs With Arrays (AoSoA)
  • How can I initialize similar structs with the same function?
  • How to remove elements of list of array/structs that have 2 common elements
  • C++ Filling a 2d Vector with Structs
  • How to store different structs in a interface for json
  • Array of structs, member alias
  • How do you call a function with an array of structs?
  • qsort with array of structs?
  • issue with Hive Serde dealing nested structs
  • Assigning an array of structs to an array of protocols
  • Why does't C allow member functions in structs?
  • Map of structs vs array of structs in Go
  • Json marshal map of structs results in empty object
  • Set of structs in Go
  • Visual Studio 2010 no color for class names and structs
  • Store C structs for multiple platform use - would this approach work?
  • Failing to change members of structs stored in two-dimensional array
  • How do I call a function that has an argument that is a pointer to an array of pointers to structs and an unspecified size
  • User defined calculation on structs/classes
  • Allocating the correct size of struct variable with sub-structs
  • sort an array of structs with multiple criteria c#
structs list of languages used
structs latest release notes
v1.0.0 v1.0.0

First release

Other projects in Go