在Go语言中有foreach结构吗? 我可以迭代一个片或数组使用for?


当前回答

下面是如何在Go中使用foreach的示例代码:

package main

import (
    "fmt"
)

func main() {

    arrayOne := [3]string{"Apple", "Mango", "Banana"}

    for index,element := range arrayOne{

        fmt.Println(index)
        fmt.Println(element)

    }

}

这是一个运行中的示例https://play.golang.org/p/LXptmH4X_0

其他回答

实际上,你可以对你的类型使用for range而不引用它的返回值:

arr := make([]uint8, 5)
i,j := 0,0
for range arr {
    fmt.Println("Array Loop", i)
    i++
}

for range "bytes" {
    fmt.Println("String Loop", j)
    j++
}

https://play.golang.org/p/XHrHLbJMEd

Go有一个类似foreach的语法。它支持数组/切片、映射和通道。

迭代数组或切片:

// index and value
for i, v := range slice {}

// index only
for i := range slice {}

// value only
for _, v := range slice {}

迭代一个地图:

// key and value
for key, value := range theMap {}

// key only
for key := range theMap {}

// value only
for _, value := range theMap {}

遍历一个通道:

for v := range theChan {}

遍历一个通道相当于从一个通道接收直到它关闭:

for {
    v, ok := <-theChan
    if !ok {
        break
    }
}

这可能是显而易见的,但你可以像这样内联数组:

package main

import (
    "fmt"
)

func main() {
    for _, element := range [3]string{"a", "b", "c"} {
        fmt.Print(element)
    }
}

输出:

abc

https://play.golang.org/p/gkKgF3y5nmt

下面是如何在Go中使用foreach的示例代码:

package main

import (
    "fmt"
)

func main() {

    arrayOne := [3]string{"Apple", "Mango", "Banana"}

    for index,element := range arrayOne{

        fmt.Println(index)
        fmt.Println(element)

    }

}

这是一个运行中的示例https://play.golang.org/p/LXptmH4X_0

我刚刚实现了这个库:https://github.com/jose78/go-collection。

这是一个如何使用Foreach循环的例子:

package main

import (
    "fmt"

    col "github.com/jose78/go-collection/collections"
)

type user struct {
    name string
    age  int
    id   int
}

func main() {
    newList := col.ListType{user{"Alvaro", 6, 1}, user{"Sofia", 3, 2}}
    newList = append(newList, user{"Mon", 0, 3})

    newList.Foreach(simpleLoop)

    if err := newList.Foreach(simpleLoopWithError); err != nil{
        fmt.Printf("This error >>> %v <<< was produced", err )
    }
}

var simpleLoop col.FnForeachList = func(mapper interface{}, index int) {
    fmt.Printf("%d.- item:%v\n", index, mapper)
}


var simpleLoopWithError col.FnForeachList = func(mapper interface{}, index int) {
    if index > 1{
        panic(fmt.Sprintf("Error produced with index == %d\n", index))
    }
    fmt.Printf("%d.- item:%v\n", index, mapper)
}

执行的结果应该是:

0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
2.- item:{Mon 0 3}
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
Recovered in f Error produced with index == 2

ERROR: Error produced with index == 2
This error >>> Error produced with index == 2
 <<< was produced

在操场上试试这段代码。