struct中的更新值不起作用

问题描述 投票:1回答:2

我有结构值和我运行循环更新值,而调试代码我看到它进入案例行像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
}
go struct
2个回答
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"
    }
}

0
投票

在元素范围内,您可以获得元素的副本。这就是为什么改变它不会改变原始价值的原因。

您可以迭代索引并更改元素。并且您不需要更改切片到指针:

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"
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.