Why can't I change the values in a range of type structure?

主宰稳场 提交于 2019-12-02 03:09:40

The Go Programming Language Specification

For statements with range clause

A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.


The Go Programming Language Specification is an easy read.

Put the updated elem iteration variable back in the chartRecords slice:

for i, elem := range chartRecords {
    elem.Count = modMe(mod, i)
    chartRecords[i] = elem
    fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name)
}

Adding these lines from a little help from my friend Russ.

Quote: Hi Victor, If I remember this correctly, when you for…range through a collection, the object returned is a copy of the original held in the collection (“value semantics”). So, the elem variable is a copy that you are assigning the count to. It’s valid code, but you aren’t updating the collection like you’re expecting. Consider adjusting your for…range loop to this:

    fmt.Printf("======NOW MODIFY VALUES THIS WAY========\r\n")                                  
    i = 0
    for idx := range chartRecords { 
        mm := modMe(mod, i)  
        chartRecords[idx].Count = mm  
        fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, chartRecords[idx].Count, chartRecords[idx].Name)  //Print out this elem.Count element in the range
        i = i + 1    
    } 

    fmt.Printf("======CHECK AGAIN AND VALUES ARE AS DESIRED========\r\n")                                       //Now lets loop through the same range
    i = 0
    for _, elem := range chartRecords {
        fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name)    //Print out this elem.Count element in the range
        i = i + 1
    } 

Now I understand better and I hope this helps other newbies like me...

Have a great day!

Victor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!