Skip to content

Instantly share code, notes, and snippets.

Last active Aug 1, 2022
What would you like to do?
Golang Enum pattern that can be serialized to json
package enum_example
import (
// TaskState represents the state of task, moving through Created, Running then Finished or Errorred
type TaskState int
const (
// Created represents the task has been created but not started yet
Created TaskState = iota
//Running represents the task has started
// Finished represents the task is complete
// Errorred represents the task has encountered a problem and is no longer running
func (s TaskState) String() string {
return toString[s]
var toString = map[TaskState]string{
Created: "Created",
Running: "Running",
Finished: "Finished",
Errorred: "Errorred",
var toID = map[string]TaskState{
"Created": Created,
"Running": Running,
"Finished": Finished,
"Errorred": Errorred,
// MarshalJSON marshals the enum as a quoted json string
func (s TaskState) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
return buffer.Bytes(), nil
// UnmarshalJSON unmashals a quoted json string to the enum value
func (s *TaskState) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.
*s = toID[j]
return nil
Copy link

jaxsong commented Dec 27, 2021

type Kind int

const (
	Unknown Kind = iota

func (t Kind) String() string {
	return [...]string{"Unknown", "Sent", "Received", "Failed", "Report"}[t]

func (t *Kind) FromString(kind string) Kind {
	return map[string]Kind{
		"Unknown":  Unknown,
		"Sent":     Sent,
		"Received": Received,
		"Failed":   Failed,
		"Report":   Report,

func (t Kind) MarshalJSON() ([]byte, error) {
	return json.Marshal(t.String())

func (t *Kind) UnmarshalJSON(b []byte) error {
	var s string
	err := json.Unmarshal(b, &s)
	if err != nil {
		return err
	*t = t.FromString(s)
	return nil

Copy link

adev73 commented Jul 14, 2022

func (t *Kind) UnMarshalJSON(b []byte) error {

Note that this should be UnmarshalJSON, without the capital "M" in the middle... other than that, works brilliantly, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment