在for循环中使用指针 [英] Using Pointers in a for loop
问题描述
我正在努力理解为什么我的代码处于一种状态而不是另一种状态.自从我讲完指针已经有一段时间了,所以我可能会生锈!
I'm struggling to understand why I have a bug in my code in one state but not the other. It's been a while since I've covered pointers, so I'm probably rusty!
基本上,我有一个用于将对象存储在内存中的存储库结构,该对象具有Store
函数.
Basically I have a repository structure I'm using to store an object in memory, that has a Store
function.
type chartsRepository struct {
mtx sync.RWMutex
charts map[ChartName]*Chart
}
func (r *chartsRepository) Store(c *Chart) error {
r.mtx.Lock()
defer r.mtx.Unlock()
r.charts[c.Name] = c
return nil
}
因此,它要做的只是将RW互斥锁锁定,并将指针添加到由标识符引用的地图上.
So all it does is put a RW mutex lock on and adds the pointer to a map, referenced by an identifier.
然后我有一个函数,该函数基本上会遍历这些对象的一部分,并将它们全部存储在存储库中.
Then I've got a function that will basically loop through a slice of these objects, storing them all in the repository.
type service struct {
charts Repository
}
func (svc *service) StoreCharts(arr []Chart) error {
hasError := false
for _, chart := range arr {
err := svc.repo.Store(&chart)
// ... error handling
}
if hasError {
// ... Deals with the error object
return me
}
return nil
}
以上方法无效,起初看起来一切正常,但是稍后尝试访问数据时,尽管键不同,但映射中的所有条目都指向同一Chart
对象.
The above doesn't work, it looks like everything works fine at first, but on trying to access the data later, the entries in the map all point to the same Chart
object, despite having different keys.
如果我执行以下操作并将指针引用移至另一个函数,则一切都会按预期进行:
If I do the following and move the pointer reference to another function, everything works as expected:
func (svc *service) StoreCharts(arr []Chart) error {
// ...
for _, chart := range arr {
err := svc.storeChart(chart)
}
// ...
}
func (svc *service) storeChart(c Chart) error {
return svc.charts.Store(&c)
}
我假设问题在于,因为循环会覆盖for
循环中对chart
的引用,所以指针引用也会更改.在独立函数中生成指针时,该引用永远不会被覆盖.是吗?
I'm assuming the issue is that because the loop overwrites the reference to the chart
in the for
loop, the pointer reference also changes. When the pointer is generated in an independent function, that reference is never overwritten. Is that right?
我觉得自己很愚蠢,但是指针不应该由&chart
生成并且与chart
引用无关吗?我还尝试在for
循环中为指针p := &chart
创建一个新变量,但这也不起作用.
I feel like I'm being stupid, but shouldn't the pointer be generated by &chart
and that's independent of the chart
reference? I also tried creating a new variable for the pointer p := &chart
in the for
loop and that didn't work either.
我应该避免在循环中生成指针吗?
Should I just avoid generating pointers in loops?
推荐答案
这是因为只有一个循环变量chart
,并且在每次迭代中都只为其分配了一个新值.因此,如果您尝试获取循环变量的地址,则在每次迭代中它都将是相同的,因此您将存储相同的指针,并且在每次迭代中(以及在循环之后,它都将覆盖该指针对象(循环变量))将保留在上一次迭代中分配的值.
This is because there is only a single loop variable chart
, and in each iteration just a new value is assigned to it. So if you attempt to take the address of the loop variable, it will be the same in each iteration, so you will store the same pointer, and the pointed object (the loop variable) is overwritten in each iteration (and after the loop it will hold the value assigned in the last iteration).
This is mentioned in Spec: For statements: For statements with range
clause:
"range"子句可以使用短变量声明(
:=
).在这种情况下,它们的类型被设置为各个迭代值的类型,并且它们的 scope 是块"for"声明的内容; 它们在每次迭代中都会重复使用.如果迭代变量是在"for"语句之外声明的,则执行后它们的值将是上一次迭代的值.
The iteration variables may be declared by the "range" clause using a form of short variable declaration (
:=
). In this case their types are set to the types of the respective iteration values and their scope is the block of the "for" statement; they are re-used in each iteration. If the iteration variables are declared outside the "for" statement, after execution their values will be those of the last iteration.
您的第二个版本有效,因为您将循环变量传递给了一个函数,因此将对其进行复制,然后存储该副本的地址(与循环变量分离).
Your second version works, because you pass the loop variable to a function, so a copy will be made of it, and then you store the address of the copy (which is detached from the loop variable).
尽管没有功能,您也可以实现相同的效果:只需创建本地副本并使用该地址的地址即可:
You can achieve the same effect without a function though: just create a local copy and use the address of that:
for _, chart := range arr {
chart2 := chart
err := svc.repo.Store(&chart2) // Address of the local var
// ... error handling
}
还请注意,您还可以存储slice元素的地址:
Also note that you may also store the address of the slice elements:
for i := range arr {
err := svc.repo.Store(&arr[i]) // Address of the slice element
// ... error handling
}
这样做的缺点是,由于您存储了指向slice元素的指针,因此只要保留了任何指针,就必须将slice的整个支持数组保存在内存中(无法对数组进行垃圾回收) .此外,您存储的指针将与切片共享相同的Chart
值,因此,如果有人修改传递的切片的图表值,则会影响您存储其指针的图表.
The disadvantage of this is that since you store pointers to the slice elements, the whole backing array of the slice would have to be kept in memory for as long as you keep any of the pointers (the array cannot be garbage collected). Moreover, the pointers you store would share the same Chart
values as the slice, so if someone would modify a chart value of the passed slice, that would effect the charts whose pointers you stored.
查看相关问题:
这篇关于在for循环中使用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!