更新结构中的值不起作用

i’ve struct with value and I run with loop to update value, while debug the code I see that it enter to the case lines like element.Type = "cccc” but after the loop exit when I look at ftr the old value exist and its not updated, what am I missing here ?

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

}

This is the struct

type FTR struct {
    Id            string     
    Mod      []Mod  
}


type Mod struct {
    Name       string
    Type       string
}

You can either use pointers:

type FTR struct {
    Id  string
    Mod []*Mod
}

Or address your items directly

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

While rangin over elements you get a copy of the element. Thats why changing it doesn't change original value.

You may iterate over indices and change elements. And you do not need change slice to pointers:

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

}