Skip to content

Instantly share code, notes, and snippets.

@necrophonic
Last active April 20, 2020 14:06
Show Gist options
  • Save necrophonic/6d8cb4ad987e32ffa0ad31ee98b35b02 to your computer and use it in GitHub Desktop.
Save necrophonic/6d8cb4ad987e32ffa0ad31ee98b35b02 to your computer and use it in GitHub Desktop.
Custom unmarshaling to a temporary struct
package main
type (
// The struct we actually want to unmarshal to
MyStruct {
name string `yaml:"name"`
age int `yaml:"age"`
flavour string `yaml:"flavour"`
} `yaml:"mystruct"`
// Temp struct mapping the same fields as the original
unmarshalMyStuct MyStruct
)
// UnmarshalYAML is called automatically by `yaml.Unmarshal` when attempting
// to unmarshal yaml into an element of the receiver type.
func (m *MyStruct) UnmarshalYAML(unmarshal func(interface{}) error) error {
// Create an instance of the unmarshaler struct. We use a
// tempororay middle stage as attempting to unmarshal to the
// _actual_ type breaks with a stack loop (I believe it recursively
// keeps calling this function and unmarshaling to itself again
// until the maximum call stack is reached)
var u unmarshalMyStruct
// Run the actual unmarshal to the temporary struct
if err := unmarshal(&u); err != nil {
return err
}
// Map the unmarshaled struct type back to the original
// so's the correct value is populated in the parent.
*m = MyStruct(u)
return nil
}
// ... main() and other functions omitted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment