Skip to content

Commit 5cf47b6

Browse files
committed
Allow string enums to use set string values in stringer function
1 parent ff30d33 commit 5cf47b6

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

main.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,15 @@ func main() {
102102
panic("could not determine underlying type for enum")
103103
}
104104

105+
visited := make(map[string]bool, 0)
106+
for i:=0; i<len(enumValues); i++{
107+
if visited[enumValues[i].Value] == true{
108+
panic("no duplicate values allowed in enum")
109+
} else {
110+
visited[enumValues[i].Value] = true
111+
}
112+
}
113+
105114
templates, err := template.New("").
106115
Funcs(TemplateFunctions). // Custom functions
107116
ParseFS(templates, "templates/*.tmpl")

templates/enum.tmpl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,11 @@ func ({{ $lt }} {{ $t }}) String() string {
4747
switch {{ $lt }} {
4848
{{- range $index, $enum := $.EnumValues }}
4949
case {{ $enum.Name }}:
50+
{{- if eq $.BaseType "string" }}
51+
return {{ $enum.Value }} {{ else }}
5052
return "{{ stringer $enum.Name }}"
5153
{{- end }}
54+
{{- end }}
5255
default:
5356
{{- if $default := $.EnumDefaultValue }}
5457
return {{ $default }}.String()

0 commit comments

Comments
 (0)