• This repository has been archived on 11/Oct/2018
  • Stars
    star
    3,811
  • Rank 11,550 (Top 0.3 %)
  • Language
    Go
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Utilities for Go structs

Archived project. No maintenance.

This project is not maintained anymore and is archived. Feel free to fork and make your own changes if needed. For more detail read my blog post: Taking an indefinite sabbatical from my projects

Thanks to everyone for their valuable feedback and contributions.

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 uninitialized
z := s.IsZero()           // Check if all fields are uninitialized

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

More Repositories

1

vim-go

Go development plugin for Vim
Vim Script
15,577
star
2

color

Color package for Go (golang)
Go
6,536
star
3

vim-go-tutorial

Tutorial for vim-go
Vim Script
2,122
star
4

gomodifytags

Go tool to modify struct field tags
Go
1,995
star
5

pool

Connection pool for Go's net.Conn interface
Go
1,331
star
6

subvim

Vim customized to be like SublimeText
C++
1,122
star
7

dotfiles

My personal dotfiles
Lua
792
star
8

set

Set data structure for Go
Go
657
star
9

structtag

Parse and modify Go struct field tags
Go
568
star
10

errwrap

Go tool to wrap and fix errors with the new %w verb directive
Go
366
star
11

semgroup

Like errgroup/waitgroup, but only runs a maximum of tasks at any time.
Go
280
star
12

faillint

Report unwanted import path and declaration usages
Go
229
star
13

hclfmt

Format and prettify HCL files
Go
227
star
14

motion

Navigation and insight in Go
Go
180
star
15

astrewrite

Go tool to walk & rewrite AST
Go
166
star
16

camelcase

Split a camelcase word into a slice of words in Go
Go
158
star
17

starhook

Manage & Analyze repositories at scale
Go
93
star
18

vim-hclfmt

Vim plugin for hclfmt
Vim Script
73
star
19

stopwatch

Stopwatch functionality for Go
Go
69
star
20

images

Images is a tool for managing machine images from multiple providers
Go
68
star
21

addlint

An example linter written with go/analysis for tutorial purposes
Go
53
star
22

gb-example

Example gb project with dependencies and CI integration
Go
47
star
23

hcl

HCL Parser and Printer in Go
Go
44
star
24

templatectl

Simple templating CLI
Go
42
star
25

twirpdemo

An example repository of using the Twirp RPC framework with Go
Go
32
star
26

talks

My personal talk slides
Go
24
star
27

unexport

Unexport notused exported identifiers in Go
Go
22
star
28

kodla-talk-2022

Code and slides for Kodla 2022
Go
20
star
29

flags

Flag parsing in Go
Go
18
star
30

vim-nginx

Nginx runtime files for Vim
Vim Script
17
star
31

dvb-t2

Software implementation of DVB-T2
Objective-C
16
star
32

sicp

My personal notes, solutions, thoughts, etc.. about SICP
16
star
33

amqp-examples

Examples to show basic amqp commands in different languages
Go
15
star
34

testmod

Testing Go modules
AMPL
11
star
35

RailsDashboard.kdapp

An easy way to learn, test and deploy Rails
CoffeeScript
7
star
36

cafetiere

An iOS app to make beautiful Coffee
Objective-C
6
star
37

koding-wiki

Koding framework docs to build KD Apps
6
star
38

blog.arsln.org-backup

Fatih Arslan's Personal Blog
CSS
4
star
39

docker-ubuntu-go

Docker image for Go and Ubuntu
Shell
4
star
40

sinerji

A gui written in PyQt4 that uses Avahi as backend for Synergy
Python
1
star
41

snippets

Snippets, code examples, etc..
C
1
star
42

pisi-vim

A vim plugin for pisi packaging
Vim Script
1
star