英文:
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()
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论