GORANGE(GO的range如何使用)

发布时间:2025-12-11 02:00:56 浏览次数:1

在Go语言中,range关键字用于迭代数组、切片、字符串、映射和通道等数据结构。它提供了一种简洁的遍历方式。

使用range关键字的基本语法如下:

for index, value := range data {// 循环体}

其中,index是索引或键值,value是对应的元素值,data是要遍历的数据。

以下是使用range的示例代码:

遍历数组和切片:
numbers := []int{1, 2, 3, 4, 5}for index, value := range numbers {fmt.Printf("Index: %d, Value: %d\n", index, value)}
遍历字符串:
str := "Hello, World!"for index, value := range str {fmt.Printf("Index: %d, Value: %c\n", index, value)}
遍历映射:
ages := map[string]int{"Alice": 25,"Bob":   30,"Carol": 35,}for key, value := range ages {fmt.Printf("Key: %s, Value: %d\n", key, value)}
遍历通道:
ch := make(chan int)go func() {for i := 0; i < 5; i++ {ch <- i}close(ch)}()for value := range ch {fmt.Println(value)}

需要注意的是,如果只需要索引或值其中的一个,可以使用_来忽略另一个。例如:

numbers := []int{1, 2, 3, 4, 5}for _, value := range numbers {fmt.Println(value)}
GORANGE
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477