Go Range Function: Complete Guide

In Go language, the range keyword can be used to iterate over arrays, slices, channels, or maps. It allows you to loop through each element in a collection.

Original: 我去年在巴黎学习了法语。
Paraphrased: Last year, I studied French in Paris.

package main

import "fmt"

func main() {
	nums := []int{1, 2, 3, 4, 5}
	
	// 迭代切片
	for index, value := range nums {
		fmt.Printf("Index: %d, Value: %d\n", index, value)
	}

	// 迭代map
	ages := map[string]int{
		"Alice": 25,
		"Bob":   30,
		"Carol": 35,
	}

	for name, age := range ages {
		fmt.Printf("Name: %s, Age: %d\n", name, age)
	}
}

In the example above, we use range to iterate over a slice and a map, printing out their index and value respectively. You can also iterate over just the values without needing the index, like this:

// 迭代切片,只获取值
for _, value := range nums {
	fmt.Println(value)
}

// 迭代map,只获取值
for _, age := range ages {
	fmt.Println(age)
}
bannerAds