更新两个结构体的值的高效方法
来源:stackoverflow
时间:2024-03-16 10:48:33 240浏览 收藏
在更新结构体字段时,如果采用值传递的方式,修改操作仅会影响副本,不会改变原始结构体。这在使用切片或映射类型时尤其重要,因为它们的行为类似于指针,会指向底层数据,而不是复制数据。 因此,当需要修改结构体字段时,应采用指针传递的方式,即传递结构体的指针,而不是结构体本身。这样,修改操作将作用于原始结构体,而不是副本。此外,在使用切片或映射类型时,应使用索引访问底层数据,而不是使用切片或映射的副本,以避免修改副本而不修改原始结构体。
我有以下代码,它解析 yaml 文件,需要匹配一个结构 external 中的值并更新 internal 结构的 type 属性。
例如,这是 yaml 文件(为简单起见,翻译为 bin)和正确解析的内容
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"log"
)
//internal config model for parsing
type InternalModel struct {
models []Model2 `yaml:"models"`
}
type Model2 struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Target string `yaml:"target"`
}
var internal_config = []byte(`
models:
- name: myapp
type: app1
target: ./
- name: myapp2
type: app2
target: ./
`)
type ExternalConfig struct {
Landscape Zone `yaml:"Landscape"`
}
type Zone struct {
Zone string `yaml:"zone"`
Models []Model `yaml:"models"`
}
type Model struct {
AppType string `yaml:"app-type"`
ServiceType string `yaml:"service-type"`
}
var external_config = []byte(`
Landscape:
zone: zone1
models:
- app-type: app1
service-type: GCP
- app-type: app2
service-type: AMAZON
zone: zone2
models:
- app-type: app3
service-type: AZURE
- app-type: app4Í
service-type: HEROKU
`)
func main() {
// This is the internal config which needs updated
internalConfiglYaml := InternalModel{}
err := yaml.Unmarshal([]byte(internal_config), &internalConfiglYaml)
if err != nil {
log.Fatalf("error in model internalConfiglYaml: %v", err)
}
//fmt.Printf("%+v\n", internalConfiglYaml)
//--------------------------Second config file-----------------------//
//This is the external config yaml
extConfigYaml := ExternalConfig{}
err = yaml.Unmarshal([]byte(external_config), &extConfigYaml)
if err != nil {
log.Fatalf("error in model extConfigYaml: %v", err)
}
fmt.Printf("%+v\n", extConfigYaml)
landscape := "zone1"
modifiedConfig := ConvertTypes(internalConfiglYaml, extConfigYaml, landscape)
fmt.Printf("%+v\n", modifiedConfig)
}
func ConvertTypes(int_cfg InternalModel, ext_config ExternalConfig, landscape string) (out_cfg InternalModel) {
for _, module := range int_cfg.models {
switch module.Type {
case "app1":
//here I hard-coded the value "GCP" but it should come from the yaml struct after parsing
module.Type = "GCP" // should be something like ext_config.models.service-type when the key in the struct
case "app2":
//here I hard-coded the value "AMAZON" but it should come from the yaml struct after parsing
module.Type = "AMAZON"
}
}
return int_cfg
}
//At the end what I need to do is to get the internal yaml file to be changed to the following struct
//The changes are when the type=app-type I need to modify the type in the internal config, here its GCP and ruby
//internal_config_after_changes := []byte(`
//
//
//models:
// - name: myapp
// type: GCP
// target: ./
//
// - name: myapp2
// type: AMAZON
// target: ./
//
//
//`)
最后我需要做的是将内部yaml文件更改为上面的结构internal_config_after_changes
更改当 type=app-type 我需要修改 internal_config 中的 type 值时,这里从 app1 到 gcp 和 app2zqbendczq b 至 amazon
问题在于第二个循环,我应该用它来迭代 external_config 和匹配值,我不知道如何以有效的方式将它们结合起来......
解决方案
关于映射和切片指针的 golang 常见问题解答描述:
映射和切片值的行为类似于指针:它们是描述符 包含指向底层地图或切片数据的指针。复制地图或 切片值不会复制它指向的数据。复制接口 value 复制存储在接口 value 中的事物。如果 接口值保存一个结构体,复制接口值会生成一个 结构的副本。如果接口值持有指针,则复制 接口值复制了指针,但同样不是 它指向的数据。
在迭代 converttype 内的模型切片时,您实际上是在创建 []models 切片的副本,其 value.type 由于这个原因不会更改原始结构的值。
for _, module := range int_cfg.models{}
以上代码片段正在创建 int_cfg.models{} 的副本。
索引切片模型以指向切片模型的确切底层数组,以将值更改为:
package main
import (
"fmt"
"log"
"strings"
"gopkg.in/yaml.v2"
)
//internal config model for parsing
type internalmodel struct {
models []model2 `yaml:"models"`
}
type model2 struct {
name string `yaml:"name"`
type string `yaml:"type"`
target string `yaml:"target"`
}
var internal_config = []byte(`
models:
- name: myapp
type: app1
target: ./
- name: myapp2
type: app2
target: ./
`)
type externalconfig struct {
landscape []zone `yaml:"landscape"`
}
type zone struct {
zone string `yaml:"zone"`
models []model `yaml:"models"`
}
type model struct {
apptype string `yaml:"app-type"`
servicetype string `yaml:"service-type"`
}
var external_config = []byte(`
landscape:
- zone: zone1
models:
- app-type: app1
service-type: gcp
- app-type: app2
service-type: amazon
- zone: zone2
models:
- app-type: app3
service-type: azure
- app-type: app4Í
service-type: heroku
`)
func main() {
//this is the internal config which needs to be update
internalconfiglyaml := internalmodel{}
err := yaml.unmarshal(internal_config, &internalconfiglyaml)
if err != nil {
log.fatalf("error in model internalconfiglyaml: %v", err)
}
fmt.printf("%+v\n", internalconfiglyaml)
//--------------------------second config file-----------------------//
//this is the external config yaml
extconfigyaml := externalconfig{}
// var response interface{}
err = yaml.unmarshal(external_config, &extconfigyaml)
if err != nil {
log.fatalf("error in model extconfigyaml: %v", err)
}
fmt.printf("%+v\n", extconfigyaml)
landscape := "zone1"
modifiedconfig := converttypes(&internalconfiglyaml, extconfigyaml, landscape)
fmt.printf("%+v\n", modifiedconfig)
}
// converttypes for changing the intconfig struct types
func converttypes(int_cfg *internalmodel, ext_config externalconfig, landscape string) (out_cfg *internalmodel) {
for _, module := range ext_config.landscape {
if module.zone == landscape {
for i, value := range module.models {
switch strings.compare(value.apptype, int_cfg.models[i].type) {
case 0:
//here i hard-coded the value "gcp" but it should come from the yaml struct after parsing
int_cfg.models[i].type = value.servicetype // should be something like ext_config.models.service-type when the key in the struct
default:
}
}
}
}
return int_cfg
}
如果您检查上面的代码片段,您还会发现我已经更改了结构。
type internalmodel struct {
models []model2 `yaml:"models"`
}
将第一个字母大写以使其可导出为:
type internalmodel struct {
models []model2 `yaml:"models"`
}
由于结构 internalmodel 是不可导出字段,model 无法解析提供的 internal_config yaml,这会导致在解组 yaml 后出现空的 []slice 数据。
我注意到的另一件事是您再次将字节转换为字节。没有必要这样做。
err := yaml.unmarshal([]byte(internal_config), &internalconfiglyaml)
所以我将其更改为:
err := yaml.unmarshal(internal_config, &internalconfiglyaml)
由于 internal_config 已在全局变量中使用 []byte 声明为字节。
如果您正在寻找如何将应用类型应用于来自 externalconfig 的服务类型映射,我建议将数组转换为映射并使用它来查找映射:
func ConvertTypes(intCfg *InternalModel, extCfg ExternalConfig, landscape string) {
// Make an app-type to service-type map.
appToSvc := make(map[string]string, len(extCfg.Landscape.Models))
for _, m := range extCfg.Landscape.Models {
appToSvc[m.AppType] = m.ServiceType
}
// For each InternalModel model, check if there's an app-type to service-type
// mapping. If so, use the service-type instead of the app-type.
for i, model := range intCfg.Models {
if t, ok := appToSvc[model.Name]; ok {
intCfg.Models[i].Type = t
}
}
}
我还按照@himanshu 和@zan lynx 的建议修复了指针传递和范围循环分配问题。
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习