Drathier
Drathier

Reputation: 14539

Range over `type x []struct` or `type y struct`?

It seems that there is no Ranger interface for ranging over custom types. Is there anything similar? Or do I have to make a method that converts the type to a slice or map?

Edit: of course I could cast x to []struct, but that would make it harder to change the underlying type of x.

Upvotes: 0

Views: 88

Answers (1)

fuz
fuz

Reputation: 93127

The range variant of the for loop is not extendable to custom collections that are not just renamed slices, maps, strings, or channels. There is no Ranger interface or anything like that. If you want to range over a custom type, consider using a for-loop like this:

for x, eof := col.Next(); x, eof = col.Next(); !eof {
    // ...
}

where Next() is a method that iterates through your collection with a signature like this:

func (*MyCollection) Next() (ItemType x, bool eof)

Upvotes: 2

Related Questions