Home >Backend Development >Golang >Why Does Copying from a Go Slice with a Range Loop Sometimes Duplicate Memory Addresses?
Reusing Memory Address When Copying from Slice in Go
You have encountered a peculiar behavior in Go where copying values from a slice using a range loop resulted in duplicated memory addresses in the output. To resolve this, you modified the code to create a temporary variable, which produced the expected distinct addresses.
This behavior arises because in the original code, the loop variable item is a pointer to the current element of the slice. As you iterate through the slice, Go reuses this pointer variable, changing its value with each iteration but keeping the same memory address. Consequently, when you assign &item to the output slice, you inadvertently duplicate the same memory address multiple times.
To prevent this reuse, your modified code creates a temporary variable i to hold a copy of the current element. This forces Go to create a new memory allocation for each iteration, resulting in unique addresses in the output slice.
To illustrate this concept, consider the following example:
package main import "fmt" type Region struct { Name string } func main() { // Create a slice of Region objects. regions := []Region{ {Name: "Central"}, {Name: "East"}, } // Original code - duplicates memory addresses fmt.Println("Original Code:") models1 := make([]Model, len(regions)) for idx, item := range regions { models1[idx] = &item } for _, m := range models1 { fmt.Println(m) } // Modified code - generates unique memory addresses fmt.Println("Modified Code:") models2 := make([]Model, len(regions)) for idx, _ := range regions { i := regions[idx] models2[idx] = &i } for _, m := range models2 { fmt.Println(m) } }
Running this code, you will notice that the original code prints duplicated memory addresses, while the modified code produces unique addresses.
The above is the detailed content of Why Does Copying from a Go Slice with a Range Loop Sometimes Duplicate Memory Addresses?. For more information, please follow other related articles on the PHP Chinese website!