Skip to content

Commit

Permalink
Allow string enums to use set string values in stringer function
Browse files Browse the repository at this point in the history
  • Loading branch information
lucvankessel committed Nov 5, 2023
1 parent ff30d33 commit 5cf47b6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
9 changes: 9 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ func main() {
panic("could not determine underlying type for enum")
}

visited := make(map[string]bool, 0)
for i:=0; i<len(enumValues); i++{
if visited[enumValues[i].Value] == true{
panic("no duplicate values allowed in enum")
} else {
visited[enumValues[i].Value] = true
}
}

templates, err := template.New("").
Funcs(TemplateFunctions). // Custom functions
ParseFS(templates, "templates/*.tmpl")
Expand Down
3 changes: 3 additions & 0 deletions templates/enum.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,11 @@ func ({{ $lt }} {{ $t }}) String() string {
switch {{ $lt }} {
{{- range $index, $enum := $.EnumValues }}
case {{ $enum.Name }}:
{{- if eq $.BaseType "string" }}
return {{ $enum.Value }} {{ else }}
return "{{ stringer $enum.Name }}"
{{- end }}
{{- end }}
default:
{{- if $default := $.EnumDefaultValue }}
return {{ $default }}.String()
Expand Down

0 comments on commit 5cf47b6

Please sign in to comment.