Review of the previous article
The previous article mainly introduces the list list and map mapping relational containers provided in the Go language, both of which are often used in our daily life. This introduces a variety of basic containers provided by Go languages, which inevitably requires querying the data in the container. So how to implement traversal? This article will introduce several commonly used and easy traversals and their use.
Container traversal
The range keyword in Go is used to iterate elements of arrays, slices, channels, or collections in a for loop. In arrays and slices it returns the value corresponding to the index of the element and the index, and in the collection it returns the key-value pair.
Traversal For many Golang's built-in containers, the form is basically the same. It mainly uses the for-range syntax. We will use the following examples to show the traversal process of arrays, slices and dictionaries. The code is as follows:
package main import "fmt" func main() { // traversal of arrays nums := [...]int{1,2,3,4,5,6,7,8} for k, v:= range nums{ // k is the subscript, v is the corresponding value (k, v, " ") } () // Traversal of slices slis := []int{1,2,3,4,5,6,7,8} for k, v:= range slis{ // k is the subscript, v is the corresponding value (k, v, " ") } () // Dictionary traversal tmpMap := map[int]string{ 0 : "Xiao Ming", 1 : "Little Red", 2 : "Xiao Zhang", } for k, v:= range tmpMap{ // k is the key value, v is the corresponding value (k, v, " ") } }
Arrays, slices, and dictionaries can be traversed in the same way through for-range. If you only need to traverse the values, you can change the unwanted keys to anonymous variable form, as shown below:
for _, v := range nums {
When traversing the keys only, the assignment of useless values can be directly omitted. During the for-range traversal, since keys and values are all assigned through copying, modifying them will not affect the changes in the members in the container, which requires us to pay more attention to in actual development.
summary
This article mainly introduces the traversal of containers. The go language mainly uses for-range syntax, and the actual cases in the text show the traversal process of arrays, slices and dictionaries respectively.
Use range on the array to pass in index and value two variables. When we do not need to use the sequence number of this element, we can use the blank "_" to omit it. However, some scenarios may indeed need to know its index.
This is the end of this article about the implementation example of Go container traversal. For more related Go container traversal content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!