Get the App
SLTechnology News&Howtos  ›  Development  › 

How to deal with Common problems in For Loop in Go language

Shulou Source: shulou.com Published: 2022-06-03 19:02:48 10月11日 Update

This article mainly explains "how to deal with common problems in For cycle in Go language". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn "how to deal with common problems in For cycle in Go language".

For loops may be used a lot in our daily coding. We need to use for loops in many business scenarios. But the for loop in golang has a big pit, can you encounter it? Go directly to the code:

We write a test class, define an array of slices, and then iterate over each element, putting the value of the element into another slice. When you cycle through finalArrays, you should output 1, 2, 3, 4 as we expect. Instead, the output is shown in the following figure:

You're so confused! Why is there such a strange phenomenon? This is caused by the scope of golang's loop variables.

In golang's for loop, the function variables created inside the loop share the same memory address, and the for loop always uses the same block of memory to receive the value of the value variable in the loop. No matter how many times you loop, the memory address of value is the same. Indeed, let's take a look at the memory address of the output value:

So, you can see that throughout the four loops, all the variable values are iterated over the address 0xc0000b8780. All four loops point to the same memory address, and the value of the last assigned Operand variable is 4, which points to this memory address, so the value of the first three times becomes 4. So how do we optimize it? We just need to define temporary variables.

We define a temporary variable tmp, assign the value of value to tmp, and the problem is solved.

Many students in the comments said that the examples are not enough to illustrate this problem. I will write a piece of code for our actual business scenario here and take a look at it.

I will not map the attributes in the Bid structure. Many novice students will commit this situation, especially those who transfer from java to go.

Thank you for reading, the above is the content of "handling common problems in For cycle in Go language". After the study of this article, I believe you have a deeper understanding of how to deal with common problems in For cycle in Go language, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Loops problems memory variables addresses processing FAQs ways languages classmates learning output business code elements content scenarios that is situations Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux MySQL Redmi NVidia Shulou Information