Documentation
¶
Overview ¶
Package structs Go library for encoding native Go structures into generic map values.
The simplest function to start with is Encoded.
Field Tags ¶
When encode to a map[string]interface{}, structs will use the field name by default to perform the mapping. For example, if a struct has a field "Username" then structs will use a key "Username".
type User struct { Username string }
You can change the behavior of structs by using struct tags. The default struct tag that structs looks for is "map" but you can customize it using EncodeWithTag.
Renaming Fields ¶
To rename the key that structs looks for, use the "map" tag and set a value directly. For example, to change the "username" example above to "user":
type User struct { Username string `map:"user"` }
Embedded Structs ¶
Embedded structs are treated as if they're another field with that name.
type Person struct { Name string `map:"name"` } type Friend struct { Person }
This would output that looks like below:
map[string]interface{}{ "name": "alice", }
Omit Empty Values ¶
When encoding from a struct to any other value, you may use the ",omitempty" suffix on your tag to omit that value if it equates to the zero value. The zero value of all types is specified in the Go specification.
For example, the zero type of a numeric type is zero ("0"). If the struct field value is zero and a numeric type, the field is empty, and it won't be encoded into the destination type.
type Source { Age int `map:",omitempty"` }
Unexported fields ¶
Since unexported (private) struct fields cannot be set outside the package where they are defined, the encoder will simply skip them.
For this input type definition:
type Exported struct { private string // this unexported field will be skipped Public string }
this map as output:
map[string]interface{}{ "Public": "I made it through!", }
Index ¶
Constants ¶
const DefaultTag = "map"
Variables ¶
This section is empty.
Functions ¶
func Encode ¶
func Encode(input interface{}) map[string]interface{}
Encode takes an input structure and uses reflection to translate it to the output map[string]interface{} with default tag "map"
func EncodeWithTag ¶
EncodeWithTag takes an input structure and uses reflection to translate it to the output map[string]interface{} with the custom tag name
Types ¶
This section is empty.