【问题标题】:Is there a foreach loop in Go?Go中有foreach循环吗?
【发布时间】:2011-12-08 14:31:44
【问题描述】:

Go 语言中有foreach 构造吗?我可以使用for 遍历切片或数组吗?

【问题讨论】:

标签: go foreach slice


【解决方案1】:
推荐的答案 Go Language

https://golang.org/ref/spec#For_range

带有“range”子句的“for”语句遍历所有条目 数组、切片、字符串或映射,或在通道上接收到的值。 对于每个条目,它将迭代值分配给相应的迭代 变量,然后执行块。

举个例子:

for index, element := range someSlice {
    // index is the index where we are
    // element is the element from someSlice for where we are
}

如果不关心索引,可以使用_

for _, element := range someSlice {
    // element is the element from someSlice for where we are
}

下划线_blank identifier,一个匿名占位符。

【讨论】:

  • 在本例中,element 是元素的 (副本)——它不是元素本身。虽然您可以分配给element,但这不会影响底层序列。
  • 我知道在 Python 和 C 中经常使用下划线作为本地化函数(即 gettext )。在 Go 中使用下划线会导致任何问题吗? Go 甚至使用相同的库进行本地化吗?
  • @SergiyKolodyaznyy Py 文档说“(gettext)函数在本地命名空间中通常别名为_()”,这只是按照惯例,它不是本地化库的一部分.下划线 _ 是一个有效的标签,它也是 Go(以及 Python 和 Scala 和其他语言)中的约定分配给 _ 以获取您不会使用的返回值。此示例中_ 的范围仅限于for 循环的主体。如果你有一个包范围的函数_,那么它将在 for 循环的范围内被隐藏。有一些本地化包,我没有看到任何使用 _ 作为函数名。
  • 请参阅下面的Moshe Revah's answer,了解更多for...range 的使用示例。包括切片、贴图和通道。
【解决方案2】:

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

迭代 arrayslice

// 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
    }
}

【讨论】:

  • 虽然 OP 只要求使用切片,但我更喜欢这个答案,因为大多数人最终也会需要其他用法。
  • 关于chan 用法的重要区别:如果作者在某个时候关闭了通道,则在通道上进行测距将优雅地退出循环。在for {v := &lt;-theChan} equivalent 中,它不会在通道关闭时退出。您可以通过第二个ok 返回值对此进行测试。 TOUR EXAMPLE
  • 读起来也是这么想的,for { ... }代表无限循环。
【解决方案3】:

以下示例展示了如何在for 循环中使用range 运算符来实现foreach 循环。

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("\n")) }} {
        action();
        if err != nil {
            return err
        }
    }
    return nil;
}

该示例遍历函数数组以统一函数的错误处理。一个完整的例子在谷歌的playground

PS:它还表明悬挂大括号对于代码的可读性是一个坏主意。提示:for 条件在 action() 调用之前结束。很明显,不是吗?

【讨论】:

  • 添加一个,for 条件在哪里结束就更清楚了:play.golang.org/p/pcRg6WdxBd - 这实际上是我第一次找到go fmt 风格的反论点,谢谢!
  • @topskip 都有效;只选择最好的一个:)
  • @FilipHaglund 如果它有效,这不是重点。关键是 IMO 在上述特定情况下更清楚 for 条件在哪里结束。
  • 在我看来,这个答案对于目标问题来说过于复杂了。
  • @AndreasHassing 如何在不引入冗余的情况下改为这样做?
【解决方案4】:

以下是如何在golang中使用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

【讨论】:

  • 有时最简单的例子是最有用的。谢谢!我没有反对其他评论者最深奥的答案——他们肯定说明了非常惯用的 Go 编程的复杂性,以至于它们变得……难以理解且难以理解——但我更喜欢你的答案:它是直截了当的用最简单的例子(这很有效,而且很明显为什么有效)。
【解决方案5】:

实际上,您可以使用 range 而不引用它的返回值,只需针对您的类型使用 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

【讨论】:

  • 很高兴知道,但在大多数情况下这不会有用
  • 同意@Sridhar,这很适合。
【解决方案6】:

是的,范围

for 循环的范围形式迭代切片或映射。

在切片上进行测距时,每次迭代都会返回两个值。第一个是索引,第二个是该索引处元素的副本。

例子:

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)
    }
}
  • 您可以通过分配给_来跳过索引或值。
  • 如果您只需要索引,请完全删除 , 值。

【讨论】:

    【解决方案7】:

    这可能很明显,但您可以像这样内联数组:

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

    输出:

    abc
    

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

    【讨论】:

      【解决方案8】:

      我刚刚实现了这个库: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
      

      Try this code in playGrounD

      【讨论】:

        猜你喜欢
        • 2021-05-28
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 2016-09-26
        • 2012-07-19
        • 2015-07-04
        • 1970-01-01
        相关资源
        最近更新 更多