Is there a foreach loop in Go?
go语言中是否有
http://golang.org DOC的CRP _ spec.html _ # for语句
A"for" statement with a"range" clause iterates through all entries
of an array, slice, string or map, or values received on a channel.
For each entry it assigns iteration values to corresponding iteration
variables and then executes the block.
作为一个例子:
1 2 3 4 | for index, element := range someSlice { // index is the index where we are // element is the element from someSlice for where we are } |
如果你真的在乎
1 2 3 | for _, element := range someSlice { // element is the element from someSlice for where we are } |
在
iterate过或螺旋阵列。
1 2 3 4 5 6 7 8 | // index and value for i, v := range slice {} // index only for i := range slice {} // value only for _, v := range slice {} |
iterate over a图:
1 2 3 4 5 6 7 8 | // key and value for key, value := range theMap {} // key only for key := range theMap {} // value only for _, value := range theMap {} |
iterate over a通道:
1 | for v := range theChan {} |
一个迭代的等效比A通道接收从A通道,直到它是封闭的。
1 2 3 4 5 6 | for { v, ok := <-theChan if !ok { break } } |
下面的例子显示如何使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | func PrintXml (out io.Writer, value interface{}) error { var data []byte var err error for _, action := range []func() { func () { data, err = xml.MarshalIndent(value,""," ") }, func () { _, err = out.Write([]byte(xml.Header)) }, func () { _, err = out.Write(data) }, func () { _, err = out.Write([]byte(" ")) }} { action(); if err != nil { return err } } return nil; } |
的例子iterates阵列unify过到的错误处理函数的函数。一个完整的例子是在google′s游乐场。
PS:所以这是它的显示是一个坏主意挂括号的readability代码。提示:
你可以使用
1 2 3 4 5 6 7 8 9 10 11 | 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++ } |
http:///P/xhrhlbjmed play.golang.org
下面是示例代码中如何使用foreach golang
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package main import ( "fmt" ) func main() { arrayOne := [3]string{"Apple","Mango","Banana"} for index,element := range arrayOne{ fmt.Println(index) fmt.Println(element) } } |
这是一个运行的例子play.golang.org https:///P/lxptmh4x _ 0
是的,范围:
环的形状和范围的iterates over a螺旋或地图。
当测距over a螺旋,双值是返回的每个迭代。第一和第二个指标,一个指标元素以这样的复制。
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 ", i, v) } for i := range pow { pow[i] = 1 << uint(i) // == 2**i } for _, value := range pow { fmt.Printf("%d ", value) } } |
- 你可以跳过或由分配到_指数值。
- 如果你想被落下的位置,指数值。
这可能是显而易见的,但你可以像内置数组:
1 2 3 4 5 6 7 8 9 10 11 | package main import ( "fmt" ) func main() { for _, element := range [3]string{"a","b","c"} { fmt.Print(element) } } |
输出:
1 | abc |
http:///P/gkkgf3y5nmt play.golang.org