Table of Contents
1.for assignment expression; relational expression or logical expression; assignment expression{}" >1.for assignment expression; relational expression or logical expression; assignment expression{}
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
" >Analysis
Home Backend Development Golang Record the pitfalls of Go's loop traversal

Record the pitfalls of Go's loop traversal

Feb 19, 2021 pm 05:38 PM
go golang

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 < 10; i++ {}
Copy after login

2.for relational expression or logical expression { }

n := 10for n > 0 {
 n--}
Copy after login

3.for { }

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

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
Copy after login

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
Copy after login

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: <div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>

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: <div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>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
Copy after login

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()
    }()}
Copy after login

②Use closure

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Golang framework development practical tutorial: FAQs Golang framework development practical tutorial: FAQs Jun 06, 2024 am 11:02 AM

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

See all articles