创建新变量避免循环变量地址问题#2164
Open
wike2019 wants to merge 1 commit intoflipped-aurora:mainfrom
Open
Conversation
Collaborator
|
有两个小问题 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
为什么需要 category := category:
在 Go 1.22 之前,循环变量 category 在每次迭代中使用同一个内存地址
如果直接使用 &category,所有指针都会指向最后一次迭代的值
虽然 Go 1.22+ 已修复此问题(每次迭代创建新变量),但显式创建新变量
可以保证代码在所有 Go 版本中都能正确工作,提高可移植性
代码意图更明确:明确表示我们要为每个节点创建独立的内存空间