在任意类型上进行范围遍历

huangapple go评论71阅读模式
英文:

Range over an arbitrary type

问题

在Go语言中,有没有一种方法可以使任意类型成为可迭代的(range-able)?例如,Python提供了__iter__()方法,非常有用。我尝试搜索答案,但没有找到结果。

英文:

Is there a way to make an arbitrary type range-able in Go? For example, Python offers __iter__(), which is really useful. I tried searching for the answer but I got no results.

答案1

得分: 3

你已经成功搜索,Go语言中不支持对任意类型进行范围遍历。

根据规范

RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .

> 在"range"子句中,右侧的表达式被称为范围表达式,可以是数组、数组指针、切片、字符串、映射或允许接收操作的通道。

英文:

You've searched successfully, there's no support for ranging over arbitrary types in Go.

From the specs:

RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .

> The expression on the right in the "range" clause is called the range expression, which may be an array, pointer to an array, slice, string, map, or channel permitting receive operations.

答案2

得分: 2

你可以使用通道来模拟它。类似于以下代码:

func (t *SomeType) Range() chan *Item {
    // 设置一个通道和一个goroutine来发送t中的项
}

for item := range t.Range() 
...
英文:

You can use channels to simulate it. Something along the lines of

func (t *SomeType) Range() chan *Item {
    // setup a channel and a go routine that sends the items from t
}

for item := range t.Range() 
...

huangapple
  • 本文由 发表于 2013年7月24日 19:53:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/17833258.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定