search
HomeBackend DevelopmentGolangRecord the pitfalls of Go's loop traversal

The following tutorial column will share with you the pitfalls of Go’s loop traversal, I hope it will be helpful to friends who need it!

Record the pitfalls of Go's loop traversalIn Golang's flow control, there are two types of loop statements: for and range.

for statement

for i := 0; i  <p><code>2.for relational expression or logical expression { }</code></p><pre class="brush:php;toolbar:false">n := 10for n > 0 {
 n--}

3.for { }

for {
 fmt.Println("hello world")
}
// 等价于
// for true {
//     fmt.Println("hello world")
// }

range statementGolang range is similar to the iterator operation and can iterate over slices, maps, arrays, strings, etc. It returns (index, value) in strings, arrays, and slices, and (key, value) in collections, but when there is only one return value, the first argument is the index or key.

str := "abc"
for i, char := range str {
    fmt.Printf("%d => %s\n", i, string(char))
}
for i := range str { //只有一个返回值
    fmt.Printf("%d\n", i)
}
nums := []int{1, 2, 3}
for i, num := range nums {
    fmt.Printf("%d => %d\n", i, num)
}
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
    fmt.Printf("%s => %s\n", k, v)
}
for k := range kvs { //只有一个返回值
    fmt.Printf("%s\n", k)
}
// 输出结果
// 0 => a
// 1 => b
// 2 => c
// 0
// 1
// 2
// 0 => 1
// 1 => 2
// 2 => 3
// a => apple
// b => banana
// a
// b

The for loop, especially the range statement, is frequently used in the normal development process, but many developers (I am one of them) often make mistakes in the following scenarios.

Scenario 1, using the variables of the loop iterator

Let’s look at an obvious mistake first:
func main() {
    var out []*int
    for i := 0; i < 3; i++ {
        // i := i
        out = append(out, &i)
    }
    fmt.Println("值:", *out[0], *out[1], *out[2])
    fmt.Println("地址:", out[0], out[1], out[2])
}
// 输出结果
// 值: 3 3 3
// 地址: 0xc000012090 0xc000012090 0xc000012090

Analysis

out

is an integer pointer array variable. In the for loop, a
i

variable is declared, and the address of i is stored in each loop. Append to the out slice, but each append is actually the i variable, so what we append is the same address, and the final value of the address is 3. Correct approach

Unlock the comments in the code

// i := i

, create a new # each time through the loop ##i
Variables.

Let’s look at a more subtle mistake: <pre class='brush:php;toolbar:false;'>func main() { a1 := []int{1, 2, 3} a2 := make([]*int, len(a1)) for i, v := range a1 { a2[i] = &amp;v } fmt.Println(&quot;值:&quot;, *a2[0], *a2[1], *a2[2]) fmt.Println(&quot;地址:&quot;, a2[0], a2[1], a2[2]) } // 输出结果 // 值: 3 3 3 // 地址: 0xc000012090 0xc000012090 0xc000012090</pre>

Analysis

Most people are here
range

This is a pitfall when assigning values ​​to variables because it is relatively secretive. In fact, the situation is the same as above. When

range
is traversing the value type,

v is a local variable and will only be initialized. Once, and then reassign the previous one every time it loops, so when assigning a value to a2[i], it is actually the same address &v, and v The final value is the value of the last element of a1, which is 3. Correct approach

a2[i]

Pass the original pointer when assigning, that is,

a2[i] = &a1[i]

②Create temporary variablet := v;a2[i] = &t
③Closure (same principle as ②), func (v int) { a2[i] = &v }(v)
The more secretive thing is: <pre class="brush:php;toolbar:false">func main() {     var out [][]int     for _, i := range [][1]int{{1}, {2}, {3}} {         out = append(out, i[:])     }     fmt.Println(&quot;Values:&quot;, out)}// 输出结果// [[3] [3] [3]]</pre>The principle is the same, no matter how many times it is traversed ,

i[:]
is always overwritten by the value of this traversal

Scenario 2, using goroutines in the loop body

func main() {
    values := []int{1, 2, 3}
    wg := sync.WaitGroup{}
    for _, val := range values {
        wg.Add(1)
        go func() {
            fmt.Println(val)
            wg.Done()
        }()
    }
    wg.Wait()}// 输出结果// 3// 3// 3

Analysis

For the main coroutine, the loop is completed quickly, and each coroutine may only start running at this time. At this time, the value of
val

has already The traversal has reached the last one, so each coroutine outputs

3
. (If the traversal data is huge and the main coroutine traversal takes a long time, the output of the goroutine will be based on the value of

val at that time, so the output result is not necessarily the same each time.) Solution

①Use temporary variables
for _, val := range values {
    wg.Add(1)
    val := val    go func() {
        fmt.Println(val)
        wg.Done()
    }()}

②Use closure

for _, val := range values {
    wg.Add(1)
    go func(val int) {
        fmt.Println(val)
        wg.Done()
    }(val)}

The above is the detailed content of Record the pitfalls of Go's loop traversal. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Logging Errors Effectively in Go ApplicationsLogging Errors Effectively in Go ApplicationsApr 30, 2025 am 12:23 AM

Effective Go application error logging requires balancing details and performance. 1) Using standard log packages is simple but lacks context. 2) logrus provides structured logs and custom fields. 3) Zap combines performance and structured logs, but requires more settings. A complete error logging system should include error enrichment, log level, centralized logging, performance considerations, and error handling modes.

Empty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsEmpty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsApr 30, 2025 am 12:23 AM

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

Comparing Concurrency Models: Go vs. Other LanguagesComparing Concurrency Models: Go vs. Other LanguagesApr 30, 2025 am 12:20 AM

Go'sconcurrencymodelisuniqueduetoitsuseofgoroutinesandchannels,offeringalightweightandefficientapproachcomparedtothread-basedmodelsinlanguageslikeJava,Python,andRust.1)Go'sgoroutinesaremanagedbytheruntime,allowingthousandstorunconcurrentlywithminimal

Go's Concurrency Model: Goroutines and Channels ExplainedGo's Concurrency Model: Goroutines and Channels ExplainedApr 30, 2025 am 12:04 AM

Go'sconcurrencymodelusesgoroutinesandchannelstomanageconcurrentprogrammingeffectively.1)Goroutinesarelightweightthreadsthatalloweasyparallelizationoftasks,enhancingperformance.2)Channelsfacilitatesafedataexchangebetweengoroutines,crucialforsynchroniz

Interfaces and Polymorphism in Go: Achieving Code ReusabilityInterfaces and Polymorphism in Go: Achieving Code ReusabilityApr 29, 2025 am 12:31 AM

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

What is the role of the 'init' function in Go?What is the role of the 'init' function in Go?Apr 29, 2025 am 12:28 AM

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

Interface Composition in Go: Building Complex AbstractionsInterface Composition in Go: Building Complex AbstractionsApr 29, 2025 am 12:24 AM

Interface combinations build complex abstractions in Go programming by breaking down functions into small, focused interfaces. 1) Define Reader, Writer and Closer interfaces. 2) Create complex types such as File and NetworkStream by combining these interfaces. 3) Use ProcessData function to show how to handle these combined interfaces. This approach enhances code flexibility, testability, and reusability, but care should be taken to avoid excessive fragmentation and combinatorial complexity.

Potential Pitfalls and Considerations When Using init Functions in GoPotential Pitfalls and Considerations When Using init Functions in GoApr 29, 2025 am 12:02 AM

InitfunctionsinGoareautomaticallycalledbeforethemainfunctionandareusefulforsetupbutcomewithchallenges.1)Executionorder:Multipleinitfunctionsrunindefinitionorder,whichcancauseissuesiftheydependoneachother.2)Testing:Initfunctionsmayinterferewithtests,b

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools