Home >Backend Development >Golang >Why Does Using Go's Range Keyword Fail to Modify Array Elements, and How Can Array Indices Provide a Solution?

Why Does Using Go's Range Keyword Fail to Modify Array Elements, and How Can Array Indices Provide a Solution?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 11:23:25217browse

Why Does Using Go's Range Keyword Fail to Modify Array Elements, and How Can Array Indices Provide a Solution?

Using Array Indices for Element Modification Instead of Range Values

In Go programming, the range keyword iterates over a collection and returns both the key and the copy of the value for each element. This behavior can hinder value modification within the loop. The following example demonstrates this issue:

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    // Attempt to modify field using range values:
    for _, e := range array {
        e.field = "foo"
    }

    // Verify that field hasn't been modified:
    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

In this code, we attempt to modify the field of each element in the array using a range loop. However, since the range returns a copy of the value, the actual elements in the array remain unchanged. This results in all field values remaining empty.

Solution: Using Array Indices

To work around this issue and modify the actual elements, you should use array indices instead of the values returned by the range loop. Here's the modified code:

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    // Modify field using array indices:
    for idx, _ := range array {
        array[idx].field = "foo"
    }

    // Verify that field has been modified:
    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

By using the index of each element instead of the value, we can directly access and modify the actual elements in the array. This ensures that the field values are correctly updated.

The above is the detailed content of Why Does Using Go's Range Keyword Fail to Modify Array Elements, and How Can Array Indices Provide a Solution?. 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