1

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
}

2 Answers2

2

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

}
Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59
1

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"
    }
}
JimB
  • 104,193
  • 13
  • 262
  • 255
  • Thanks i've close the question , What is the preferred direction , option 1 or two, for your POV –  Dec 21 '17 at 16:25
  • @Ninawatcher: pointers allow for more flexibility, especially if you need to differentiate between and empty string and no setting at all. Either way is fine depending on your needs. – JimB Dec 21 '17 at 16:27