From c0a4a544de1e0afe3cdc4623bc1e0c966aee1ea8 Mon Sep 17 00:00:00 2001 From: Luc van Kessel Date: Sun, 5 Nov 2023 15:46:05 +0100 Subject: [PATCH] Allow string enums to use set string values in stringer function --- main.go | 9 +++++++++ templates/enum.tmpl | 4 ++++ 2 files changed, 13 insertions(+) diff --git a/main.go b/main.go index 0d84110..ec86a26 100644 --- a/main.go +++ b/main.go @@ -102,6 +102,15 @@ func main() { panic("could not determine underlying type for enum") } + visited := make(map[string]bool, 0) + for i := range enumValues{ + 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") diff --git a/templates/enum.tmpl b/templates/enum.tmpl index acc02d1..458090e 100644 --- a/templates/enum.tmpl +++ b/templates/enum.tmpl @@ -47,8 +47,12 @@ 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()