在Go语言中有foreach结构吗? 我可以迭代一个片或数组使用for?
当前回答
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
}
}
其他回答
我看到很多使用范围的例子。只要注意一下,这个范围就会创建一个你迭代的对象的副本。如果对foreach范围内的内容进行更改,则不会更改原始容器中的值,在这种情况下,您将需要一个传统的for循环,其中包含一个递增的索引和遵循索引引用。例如:
for i := 0; i < len(arr); i++ {
element := &arr[i]
element.Val = newVal
}
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
}
}
下面是如何在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形式在片或映射上迭代。
当范围超过一个片时,每次迭代都会返回两个值。第一个是索引,第二个是该索引处元素的副本。
例子:
package main
import "fmt"
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
}
可以通过赋值给_来跳过索引或值。 如果只需要索引,则完全删除,值。
我刚刚实现了这个库: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
在操场上试试这段代码。