我的结构有价值,我运行循环来更新值,同时调试代码
我看到它进入像element.Type = "cccc”
这样的案例行,但是在我查看循环退出之后
在ftr,旧值存在且未更新,我在这里缺少什么?
ftr := FTR{}
err = yaml.Unmarshal([]byte(yamlFile), &ftr)
for index, element := range ftr.Mod{
switch element.Type {
case “aaa”, “bbbb”:
element.Type = "cccc”
case "htr”:
element.Type = "com"
case "no":
element.Type = "jnodejs"
case "jdb”:
element.Type = "tomcat"
}
}
这是结构
type FTR struct {
Id string
Mod []Mod
}
type Mod struct {
Name string
Type string
}
答案 0 :(得分:1)
您可以使用指针:
type FTR struct {
Id string
Mod []*Mod
}
或直接处理您的商品
for i := range ftr.Mod {
switch ftr.Mod[i].Type {
case "aaa", "bbbb":
ftr.Mod[i].Type = "cccc"
case "htr":
ftr.Mod[i].Type = "com"
case "no":
ftr.Mod[i].Type = "jnodejs"
case "jdb":
ftr.Mod[i].Type = "tomcat"
}
}
答案 1 :(得分:0)
在对元素进行rangin时,您会获得该元素的副本。这就是为什么改变它并不会改变原始价值。
您可以迭代索引并更改元素。而且你不需要改变切片到指针:
type FTR struct {
Id string
Mod []Mod
}
for index := range ftr.Mod{
switch ftr.Mod[index].Type {
case “aaa”, “bbbb”:
ftr.Mod[index].Type = "cccc”
case "htr”:
ftr.Mod[index].Type = "com"
case "no":
ftr.Mod[index].Type = "jnodejs"
case "jdb”:
ftr.Mod[index].Type = "tomcat"
}
}