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.
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.
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()
...