Created
November 4, 2023 09:32
-
-
Save willmurphyscode/9e9e65b7c090252dcb2e261fdd55b29b to your computer and use it in GitHub Desktop.
mapstructure example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
Running this fails to populate the the embedded struct:
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}}