Home >Backend Development >Golang >Why Doesn't Modifying a Struct in a Go Range Loop Change the Original Slice?
Why can't I change the values in a range of type structure?
The Go Programming Language Specification states that for statements with a range clause, "for each entry it assigns iteration values to corresponding iteration variables if present and then executes the block."
In this case, you are iterating through a slice of structures using the range statement. When you modify a field of a structure in the range, you are only modifying the iteration variable, not the underlying structure in the slice.
To modify the underlying structure, you need to access it directly using the index of the iteration variable.
For example, the following code correctly modifies the values in the 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) }
The above is the detailed content of Why Doesn't Modifying a Struct in a Go Range Loop Change the Original Slice?. For more information, please follow other related articles on the PHP Chinese website!