• Stars
    star
    784
  • Rank 58,032 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created over 7 years ago
  • Updated 3 months ago

Reviews

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

Repository Details

Initialize structs with default values

defaults

CircleCI codecov GitHub release License

Initialize structs with default values

  • Supports almost all kind of types
    • Scalar types
      • int/8/16/32/64, uint/8/16/32/64, float32/64
      • uintptr, bool, string
    • Complex types
      • map, slice, struct
    • Nested types
      • map[K1]map[K2]Struct, []map[K1]Struct[]
    • Aliased types
      • time.Duration
      • e.g., type Enum string
    • Pointer types
      • e.g., *SampleStruct, *int
  • Recursively initializes fields in a struct
  • Dynamically sets default values by defaults.Setter interface
  • Preserves non-initial values from being reset with a default value

Usage

package main

import (
	"encoding/json"
	"fmt"
	"math/rand"

	"github.com/creasty/defaults"
)

type Gender string

type Sample struct {
	Name    string `default:"John Smith"`
	Age     int    `default:"27"`
	Gender  Gender `default:"m"`
	Working bool   `default:"true"`

	SliceInt    []int    `default:"[1, 2, 3]"`
	SlicePtr    []*int   `default:"[1, 2, 3]"`
	SliceString []string `default:"[\"a\", \"b\"]"`

	MapNull            map[string]int          `default:"{}"`
	Map                map[string]int          `default:"{\"key1\": 123}"`
	MapOfStruct        map[string]OtherStruct  `default:"{\"Key2\": {\"Foo\":123}}"`
	MapOfPtrStruct     map[string]*OtherStruct `default:"{\"Key3\": {\"Foo\":123}}"`
	MapOfStructWithTag map[string]OtherStruct  `default:"{\"Key4\": {\"Foo\":123}}"`

	Struct    OtherStruct  `default:"{\"Foo\": 123}"`
	StructPtr *OtherStruct `default:"{\"Foo\": 123}"`

	NoTag    OtherStruct // Recurses into a nested struct by default
	NoOption OtherStruct `default:"-"` // no option
}

type OtherStruct struct {
	Hello  string `default:"world"` // Tags in a nested struct also work
	Foo    int    `default:"-"`
	Random int    `default:"-"`
}

// SetDefaults implements defaults.Setter interface
func (s *OtherStruct) SetDefaults() {
	if defaults.CanUpdate(s.Random) { // Check if it's a zero value (recommended)
		s.Random = rand.Int() // Set a dynamic value
	}
}

func main() {
	obj := &Sample{}
	if err := defaults.Set(obj); err != nil {
		panic(err)
	}

	out, err := json.MarshalIndent(obj, "", "	")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(out))

	// Output:
	// {
	// 	"Name": "John Smith",
	// 	"Age": 27,
	// 	"Gender": "m",
	// 	"Working": true,
	// 	"SliceInt": [
	// 		1,
	// 		2,
	// 		3
	// 	],
	// 	"SlicePtr": [
	// 		1,
	// 		2,
	// 		3
	// 	],
	// 	"SliceString": [
	// 		"a",
	// 		"b"
	// 	],
	// 	"MapNull": {},
	// 	"Map": {
	// 		"key1": 123
	// 	},
	// 	"MapOfStruct": {
	// 		"Key2": {
	// 			"Hello": "world",
	// 			"Foo": 123,
	// 			"Random": 5577006791947779410
	// 		}
	// 	},
	// 	"MapOfPtrStruct": {
	// 		"Key3": {
	// 			"Hello": "world",
	// 			"Foo": 123,
	// 			"Random": 8674665223082153551
	// 		}
	// 	},
	// 	"MapOfStructWithTag": {
	// 		"Key4": {
	// 			"Hello": "world",
	// 			"Foo": 123,
	// 			"Random": 6129484611666145821
	// 		}
	// 	},
	// 	"Struct": {
	// 		"Hello": "world",
	// 		"Foo": 123,
	// 		"Random": 4037200794235010051
	// 	},
	// 	"StructPtr": {
	// 		"Hello": "world",
	// 		"Foo": 123,
	// 		"Random": 3916589616287113937
	// 	},
	// 	"NoTag": {
	// 		"Hello": "world",
	// 		"Foo": 0,
	// 		"Random": 6334824724549167320
	// 	},
	// 	"NoOption": {
	// 		"Hello": "",
	// 		"Foo": 0,
	// 		"Random": 0
	// 	}
	// }
}

More Repositories

1

dotfiles

Stellar productivity
Vim Script
103
star
2

rid

Run commands in container as if were native. Stress-free dockerized development environment finally arrived
Go
57
star
3

Keyboard

Master of keyboard is master of automation (Key remapper implementation in Swift)
Swift
54
star
4

css-better-practice

Repo for "Clean and Unbreakable CSS"
CSS
9
star
5

jsonity

The most sexy language for building JSON in Ruby
Ruby
9
star
6

go-nkf

nkf binding for Golang
C
8
star
7

roka

Romaji to kana converter
Ruby
8
star
8

find_t

Find locale files where translation for key is defined
Ruby
7
star
9

i18n_flow

[beta] Manage translation status in YAML file
Ruby
7
star
10

ansible-playbooks-example

Example playbooks using https://github.com/creasty/ansible-roles
5
star
11

delta_test

It's kinda "delta update" for RSpec
Ruby
5
star
12

touth

Secure and simple token based authentication for Rails
Ruby
5
star
13

apperrors

[DEPRECATED] Better error handling solution especially for application server
Go
4
star
14

configo

Definitive configuration utility in Golang
Go
4
star
15

animating_tesseract

OpenGL sample of a tesseract performing rotation
C++
4
star
16

go-server-boilerplate

Boilerplate for API server in Golang
Go
3
star
17

kt-graph

Analyze & visualize class/type dependencies within your Kotlin codebase
TypeScript
3
star
18

vscode-pattern-switch

Switch the text under cursor to alternative patterns
TypeScript
3
star
19

candle.vim

Candle theme for Vim https://github.com/creasty/candle-theme
Vim Script
3
star
20

aws-sns-push

Send SNS push notifications painlessly from terminal
Go
3
star
21

herdic

A command line HTTP client intended to create and test API documentation with ease
Ruby
3
star
22

doorkeeper_assertion_flow

[DEPRECATED] OAuth assertion flow patch for doorkeeper
Ruby
3
star
23

es-workshop

Ruby
2
star
24

go-easing

Golang library for easing functions
Go
2
star
25

vscode-candle-theme

Low-contrast dark theme
JavaScript
2
star
26

go-levenshtein

Levenshtein algorithm in Golang (with C ext)
Go
2
star
27

require

RequireJS γ―γ‚γ‚“γΎγ‚Šγ‚€γ‚±γ¦γͺいとか言ってみる
JavaScript
2
star
28

raycast-material-icons

Search Material Icons in Raycast
TypeScript
2
star
29

terraform

Infrastructure as Code
HCL
2
star
30

ansible-roles

The collection of common reusable roles for web application server
Ruby
2
star
31

vscode-altr

Switching among related files
TypeScript
2
star
32

homebrew-tools

@creasty's toolbox for Homebrew
Ruby
2
star
33

i18n_interpolation_spec

RSpec matchers for testing the completeness of interpolation arguments in locale files
Ruby
2
star
34

animation-essential

Tiny animation library designed with simplicity and modernity at its core
TypeScript
1
star
35

dockerfiles

Collection of CLI tools that run as a container
TLA
1
star
36

strategy-frameworks

Frameworks that facilitate strategic thoughts
1
star
37

creasty-styleguide

1
star
38

geohash_ruby

Geohash en/decode library written in ruby
Ruby
1
star
39

opfmt

[Experimental] Format operators and delimiters as you type, using tree-sitter
Lua
1
star