Skip to content

Commit

Permalink
generate: add New function for all types, add docs
Browse files Browse the repository at this point in the history
The New function should likely be used in favor of any manual struct
creation + defaulting.
  • Loading branch information
twmb committed Oct 9, 2020
1 parent 21f9e9b commit 2262f3a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
12 changes: 12 additions & 0 deletions generate/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,19 @@ func (s Struct) WriteDecodeFunc(l *LineWriter) {
}

func (s Struct) WriteDefaultFunc(l *LineWriter) {
l.Write("// Default sets any default fields. Calling this allows for future compatibility")
l.Write("// if new fields are added to %s.", s.Name)
l.Write("func (v *%s) Default() {", s.Name)
s.WriteDefault(l)
l.Write("}")
}

func (s Struct) WriteNewFunc(l *LineWriter) {
l.Write("// New%[1]s returns a default %[1]s", s.Name)
l.Write("// This is a shortcut for creating a struct and calling Default yourself.")
l.Write("func New%[1]s() %[1]s {", s.Name)
l.Write("var v %s", s.Name)
l.Write("v.Default()")
l.Write("return v")
l.Write("}")
}
3 changes: 2 additions & 1 deletion generate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,8 +365,9 @@ func main() {
s.WriteDecodeFunc(l)
}

// everything gets a default function
// everything gets a default and new function
s.WriteDefaultFunc(l)
s.WriteNewFunc(l)
}

l.Write("// RequestForKey returns the request corresponding to the given request key")
Expand Down

0 comments on commit 2262f3a

Please sign in to comment.