Created
March 28, 2023 10:20
-
-
Save mortymacs/904f6a447996a75108d930b686a0579b to your computer and use it in GitHub Desktop.
enum to string / string to enum in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Event uint8 | |
const ( | |
Create Event = iota | |
Delete | |
Update | |
) | |
func (e Event) String() string { | |
return map[Event]string{Create: "create", Delete: "delete", Update: "update"}[e] | |
} | |
func FromString(data string) Event { | |
return map[string]Event{ | |
"create": Create, | |
"delete": Delete, | |
"update": Update, | |
}[data] | |
} | |
func main() { | |
a := Delete | |
fmt.Println(a) | |
b := "update" | |
fmt.Println(FromString(b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment