Home >Backend Development >Golang >Why Doesn't Modifying a Struct in a Go Range Loop Change the Original Slice?

Why Doesn't Modifying a Struct in a Go Range Loop Change the Original Slice?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 08:38:11391browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn