Skip to content

Instantly share code, notes, and snippets.

@ngraham20
Created March 28, 2024 22:08
Show Gist options
  • Save ngraham20/59412260586e00fd82c8b990a3b50b47 to your computer and use it in GitHub Desktop.
Save ngraham20/59412260586e00fd82c8b990a3b50b47 to your computer and use it in GitHub Desktop.
Writing a custom unmarshal function for YAML in Go
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v3"
)
type Blocktype uint8
const (
Unknown Blocktype = iota
Stone
Copper
Iron
Gold
Dirt
)
type Block struct {
Blocktype Blocktype `yaml:"blocktype"`
// How long should it take to "punch" the block
Health uint16 `yaml:"health"`
}
func (b Blocktype) String() string {
switch b {
case Stone:
return "Stone"
case Copper:
return "Copper"
case Iron:
return "Iron"
case Gold:
return "Gold"
case Dirt:
return "Dirt"
default:
return "Unknown Block Type"
}
}
func (b *Blocktype) UnmarshalYAML(unmarshal func(interface{}) error) error {
var blocktypes string
if err := unmarshal(&blocktypes); err != nil {
return err
}
switch blocktypes {
case "Stone":
*b = Stone
case "Copper":
*b = Copper
case "Iron":
*b = Iron
case "Gold":
*b = Gold
case "Dirt":
*b = Dirt
default:
*b = Unknown
}
return nil
}
func main() {
var data = `
blocktype: Stone
health: 32
`
var b Block
err := yaml.Unmarshal([]byte(data), &b)
if err != nil {
log.Fatalf("cannot unmarshal data: %v", err)
}
fmt.Println(b.Blocktype)
fmt.Println(b.Health)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment