Go 中的 Range 关键字


2022年1月26日, Learn eTutorial
2126

在本教程中,您将学习如何在Go编程语言中迭代不同的数据类型。

Golang中的range是什么?

Range是Go编程语言中用于迭代数据结构的关键字,例如数组结构体通道字符串切片map

如何在Golang中声明range?

Range用于循环或迭代一些给定的表达式,这些表达式通常会计算一个数组结构体通道字符串切片map。关键字range描述了迭代。

如何在Go中对数组使用range?

下面的程序展示了range关键字如何用于迭代数组数据类型。

在数组中使用range的程序


package main
import "fmt"

func main() {
        
    //array declaration
    colors := [3]string{"blue", "orange", "yellow"} 
    //range
    for idx, c := range colors {

        fmt.Println("Color -->", c, "@ index :", idx)
    }
}

迭代字符串值数组。名为color的数组声明了“blue”、“orange”、“yellow”的值。数组的大小为3。range关键字在每个索引上迭代color,并打印值,如输出所示。

输出


Color --> blue @ index : 0
Color --> orange @ index : 1
Color --> yellow @ index : 2

如何在Golang中使用range处理切片?

让我们通过一个例子来理解。数组和切片的声明几乎相同,只是我们在声明时不会指定切片的大小。

为了更好地理解,您可以参考我们之前的数组切片教程。

在切片中使用range的程序


package main
import "fmt"

func main() {
    
    // Creating a slice using the var keyword
    var slice1 = []string{"learn", "e", "tutorials"}

    //range
    for idx, s := range slice1{
fmt.Println("slice1 -->", s, "@ index :", idx)
}
}

输出


slice1 --> learn @ index : 0
slice1 --> e @ index : 1
slice1 --> tutorials @ index : 2

如何在Golang中使用range处理map?

下面的示例使用range来迭代Golang的map。在给定的示例中,range关键字迭代一个站点map的范围,其中键和值都是字符串。


package main
import "fmt"

func main() {
    
   site := map[string]string{            //map declaration

        "L": "Learn", 
        "e": "e",
        "T": "Tutorials",
    } 

    for k, v := range site {

        fmt.Println(k, "=>", v)
    }

    fmt.Println("----------------------")

    for k := range site {

        fmt.Println(k, "=>", site[k])
    }

输出


L => Learn
e => e
T => Tutorials
----------------------
L => Learn
e => e
T => Tutorials

如何在Golang中使用range处理字符串?

下面的示例使用range来迭代Golang的字符串。range关键字迭代文本字符串的范围以提供下面的输出。


package main
import ("fmt")

func main() {
/* var keyword assigns variable text with value “Golang” of string type */
  var text string = "Golang"
  
  for idx, t := range text {

        fmt.Printf(" index %d %c\n", idx, t)
    }

输出


index 0 G
 index 1 o
 index 2 l
 index 3 a
 index 4 n
 index 5 g
Type: string, value: Golang

如何在Golang中使用range处理通道?

在Go编程语言中,通道是Goroutines用来相互通信的管道。下面的程序使用range关键字来迭代Golang中的通道。


package main
import "fmt"

func main() {
    
    ch := make(chan string)  // channel declaration
    go func() {

        ch <- "hello"
        ch <- "Learn"
        ch <- "eTutorials"
        
        close(ch)
    }()

    for n := range ch {   // range

        fmt.Println(n)
    }
}

输出


hello
Learn
eTutorials