Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created March 28, 2023 10:20
Show Gist options
  • Save mortymacs/904f6a447996a75108d930b686a0579b to your computer and use it in GitHub Desktop.
Save mortymacs/904f6a447996a75108d930b686a0579b to your computer and use it in GitHub Desktop.
enum to string / string to enum in Go
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