Home > Backend Development > Golang > How to use range for iteration in golang

How to use range for iteration in golang

PHPz
Release: 2023-04-18 15:40:31
Original
596 people have browsed it

range is a keyword in the Go language that is used to iterate arrays, slices, channels and other collection types. Using the range keyword syntax can make the code more concise and clear. When using range to iterate, you need to pay attention to some details and differences in different scenarios.

  1. Iterating over arrays and slices

When iterating over arrays and slices, range returns two values: the index and the element value. One of the values ​​can be omitted using the _ placeholder.

Example:

arr := [5]int{1, 2, 3, 4, 5}
for index, value := range arr {
    fmt.Printf("index: %d, value: %d\n", index, value)
}

sli := []string{"hello", "world", "golang"}
for i, v := range sli {
    fmt.Printf("i: %d, v: %s\n", i, v)
}
Copy after login

When iterating an array or slice, if you only need the index or element value, you can use the _ placeholder to ignore the corresponding variable. For example:

arr := [5]int{1, 2, 3, 4, 5}
for index, _ := range arr {
    fmt.Printf("index: %d\n", index)
}

sli := []string{"hello", "world", "golang"}
for i := range sli {
    fmt.Printf("i: %d\n", i)
}
Copy after login
  1. Iterate over map

When iterating over map, range returns two values: key and value. The difference from an array is that key-value pairs are returned instead of indexes and element values.

Example:

m := map[string]int{"a":1, "b":2, "c":3}
for key, value := range m {
    fmt.Printf("key: %s, value: %d\n", key, value)
}
Copy after login

You can also use _ when iterating over the map to ignore one of the values:

m := map[string]int{"a":1, "b":2, "c":3}
for k := range m {
    fmt.Println("key:", k)
}
Copy after login
  1. Iterate over the string

Iterate When it is a string, range returns two values, the first value is the index of the character, and the second value is the character value at this index. It should be noted that during program compilation, the string is converted into a byte array, so bytes are iterated rather than characters.

Example:

str := "hello,世界!"
for index, ch := range str {
    fmt.Printf("index: %d, char: %c\n", index, ch)
}
Copy after login
  1. Iteration channel

When iterating the channel, the range will continue to block, waiting for content to be read in the channel. The range loop terminates when the channel is closed or the read is complete. The variable in the range loop is the variable that accepts the channel value.

Example:

ch := make(chan int, 10)
go func() {
    for i := 0; i < 10; i++ {
        ch <- i
    }
    close(ch)
}()

for val := range ch {
    fmt.Println("value:", val)
}
Copy after login

When using channels, special attention should be paid to the fact that if the value in the channel is not read, the program will freeze. You can solve this problem by using buffered channels or using select statements.

Buffer channel example:

ch := make(chan int, 10)
go func() {
    for i := 0; i < 10; i++ {
        ch <- i
    }
    close(ch)
}()

for {
    select {
    case val, ok := <-ch:
        if !ok {
            return
        }
        fmt.Println("value:", val)
    default:
        // 通道中没有值可读
    }
}
Copy after login
  1. Loop variable reuse

When using range for loop iteration, you must pay attention to the issue of loop variable reuse . When using a variable inside a loop, it needs to be copied to a new variable, otherwise data overwriting problems will occur.

Example:

// 错误示例
sli := []int{1, 2, 3}
for _, v := range sli {
    go func() {
        fmt.Println(v) // 输出结果都是 3
    }()
}

// 正确示例
sli := []int{1, 2, 3}
for _, v := range sli {
    val := v // 复制变量
    go func() {
        fmt.Println(val)
    }()
}
Copy after login

In short, range is a very practical keyword in the Go language, which can help us iterate the elements in the collection. When using range, you need to pay attention to the difference in return values ​​when iterating different types of collections, as well as the issue of loop variable reuse.

The above is the detailed content of How to use range for iteration in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template