在GO编程领域中合并了相同结构的字段与JSON编码
类型config struct { 路径字符串 ID字符串 键字符串 ADDR字符串 大小UINT64 } var DefaultConfig = Config{"", "", "", "", 0}And a configuration loaded from a file, such as:
var FileConfig = Config{"", "file_id", "", "file_addr", 0}
type Config struct { path string id string key string addr string size uint64 } var DefaultConfig = Config{"", "", "", "", 0}
最初,您可以利用此任务的反射来思考:
b:= reflect.valueof(默认).elem() o:=反射。valueof(file).elem() 对于我:= 0; iimport( “编码/JSON” “弦” ) const filecontent =`{“ id”:“ file_id”,“ addr”:“ file_addr”,“ size”:100}`: func umarshalconfig(conf *config,content string)错误{ 返回json.newdecoder(strings.newreader(content))。解码(conf) } func mergeconfigs(defconfig *config,fileconfig *config)错误{ 如果err:= umarshalconfig(defconfig,filecontent); err!= nil { 返回错误 } 对于_,v:= range fileconfig { defconfig [v.key] = v.value } 返回无 }
在此解决方案中,FileConfig未贴在默认配置中。编码/JSON软件包处理设置字段值的所有复杂性,包括缺失值(默认值为其零值)和文件指定的值,这些值覆盖了默认值。通过使用UnmarShaling,您可以利用简单有效的解决方案来确保与Fileconfig字段相同的合并结构,从而使该fieconfig字段均可为fileconfig offig five five five Inde Is Is Inde Is Is Inde Is Is Inde Indive [
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3