This is a creation in Article, where the information may have evolved or changed.
The use of Golang for development also has a period of time, the development of their own problems encountered in this summary, for other students reference.
Programming errors include obvious and not obvious, and here is not a distinction, you have to consider their own.
1. Use the for range to traverse the Slice/array problem
The error code is as follows:
for key, data: = Range codecacheall.codelist {
if _, OK: = App.codecachedatalist[data. Scode]; OK {
& Nbsp;delete (app.codecachedatalist, data. Scode)
}
App.codecachedatalist[data. Scode] = &data
}
which CodeList is []mystruct type, codecachedatalist is the map[string]*mystruct type .
The purpose of the code snippet is to iterate through the array and store pointers to the structure based on the Scode field in the map, so there is an implicit problem with the write, do not know crossing found?
The code runs right, but the results are too far apart, by printing the value of codecachedatalist, will find all the key is different, but all the value is pointing to the same memory address, this is a potential misunderstanding, no longer debugging is difficult to find.
Change to the following code is no problem:
for Key, Data: = Range codecacheall.codelist {
& nbsp; if _, OK: = App.codecachedatalist[data. Scode]; OK {
& Nbsp;delete (app.codecachedatalist, data. Scode)
}
App.codecachedatalist[data. Scode] = &codecacheall.codelist[key]
}
comparing the above can be found that the assignment is not the same way, the problem is that the array assignment is the value of the transfer, each time for loop data is reallocated space, set different values, its memory address has changed, not Codelist[i] memory address, and the last value is the value of the last loop allocation, so all pointers point to this address.
So one thing to summarize: when traversing the value of slice or map, the last pointer passed is to refer to the original value instead of the temporary variable.
2. To be Continued ...