Skip to content

Instantly share code, notes, and snippets.

@willmurphyscode
Created November 4, 2023 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willmurphyscode/9e9e65b7c090252dcb2e261fdd55b29b to your computer and use it in GitHub Desktop.
Save willmurphyscode/9e9e65b7c090252dcb2e261fdd55b29b to your computer and use it in GitHub Desktop.
mapstructure example
package main
import (
"fmt"
"github.com/mitchellh/mapstructure"
)
type moduleConfig struct {
ModuleBool bool `yaml:"module-bool" mapstructure:"module-bool"`
}
type specialModuleConfig struct {
*moduleConfig `yaml:",inline" mapstructure:",squash"`
SpecialModuleBool bool `yaml:"special-module-bool" mapstructure:"special-module-bool"`
}
type TopLevelConfig struct {
Module1 moduleConfig `yaml:"module-1" mapstructure:"module-1"`
Module2 specialModuleConfig `yaml:"module-2" mapstructure:"module-2"`
}
func main() {
theMap := map[string]any{
"module-1": map[string]any{
"module-bool": true,
},
"module-2": map[string]any{
"module-bool": true,
"special-module-bool": true,
},
}
configPtr := &TopLevelConfig{}
mapstructure.Decode(theMap, configPtr)
fmt.Printf("%+v\n", *configPtr)
}
@willmurphyscode
Copy link
Author

Running this fails to populate the the embedded struct:

❯ go run main.go
{Module1:{ModuleBool:true} Module2:{moduleConfig:<nil> SpecialModuleBool:true}}

But if I remove the * on the beginning of line 14, the code works as expected:

❯ vi main.go # remove * from beginning of line 14
❯ go run main.go
{Module1:{ModuleBool:true} Module2:{moduleConfig:{ModuleBool:true} SpecialModuleBool:true}}

@willmurphyscode
Copy link
Author

It looks like maybe this is a language limitation, not a mapstructure limitation: https://go-review.googlesource.com/c/go/+/53643.

There's some interesting discussion at golang/go#21357.

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