On the first day of the Dragon Boat Holiday, everyone has a healthy Dragon Boat Festival.

This is the 12th day of my participation in Gwen Challenge

These reviews

The previous article mainly introduced the list and Map mapping relational containers provided in Go language, which are commonly used in our daily life. Introduced a variety of Go language provided by the basic container, it is inevitable to query the data in the container, so how to achieve traversal? This article will describe several common easy traversals and their use.

Container traversal

The range keyword in Go is used to iterate over elements of an array, slice, channel, or map in a for loop. It returns the index of the element and its value in arrays and slices, and key-value pairs in collections.

Traversal is the same for many of Golang’s built-in containers, mainly through the for-range syntax. We’ll use the following example to show the traversal process for arrays, slicing, and dictionaries, as shown below:

package main

import "fmt"

func main(a)  {

	// Array traversal
	nums := [...]int{1.2.3.4.5.6.7.8}
	for k, v:= range nums{
		// k is the subscript and v is the corresponding value
		fmt.Println(k, v, "")
	}

	fmt.Println()

	// Slice traversal
	slis := []int{1.2.3.4.5.6.7.8}
	for k, v:= range slis{
		// k is the subscript and v is the corresponding value
		fmt.Println(k, v, "")
	}

	fmt.Println()

	// dictionary traversal
	tmpMap := map[int]string{
		0 : "Xiao Ming".1 : "Little red".2 : "Zhang",}for k, v:= range tmpMap{
		// k is the key value and v is the corresponding value
		fmt.Println(k, v, "")}}Copy the code

Arrays, slices, and dictionaries can be traversed in the same way with a for-range. If you only need to iterate over values, you can change the unwanted keys to anonymous variables, as shown below:

for _, v := range nums {
Copy the code

Assignments of useless values can be omitted when traversing only keys. In the process of for-range traversal, because the keys and values are assigned by copy, changing them does not affect the changes of the container members, which needs to be paid more attention in actual development.

summary

This article mainly introduces the traversal of containers. The for-range syntax is mainly used in GO language. The actual cases in this paper respectively show the traversal process of array, slice and dictionary.

Using range on an array passes in the index and value variables. When we do not need to use the ordinal of the element, we can omit it by using the whitespace “_”. However, some scenarios might actually need to know its index.