-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: iter: Allow nil iterators #68931
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Related Issues and Documentation (Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.) |
See #65629 (comment). |
Thanks @gabyhelp, @thepudds! Not sure how did I miss the other thread, because I did run a search for various forms of "nil iterator". Now at least I understand the behavior, although I disagree quite a bit with the decision. Maybe it would be useful to document this behavior somewhere in the |
Hi @burdiyan, maybe it could be more explicit, but it's maybe at least arguably implied by the spec? From the "For statements with range clause" section (emphasis added):
and from the "Calls" section:
|
It's too late to revisit #65629, but package iter could have a |
Thanks @thepudds, the revisited spec is what I missed to read! Similar to what @earthboundkid is suggesting, I propose adding a few convenience functions to the // NopSeq is a convenience function
// which returns an empty no-op Seq
// that is safe to range over.
func NopSeq[T any]() Seq[T] {
return func(func(T) bool) {}
}
// NopSeq2 is the same as NopSeq, but for Seq2.
func NopSeq2[K, V any]() Seq2[K, V] {
return func(func(K, V) bool) {}
} The presence of these functions would presumably indicate that ranging over a nil iterator is not safe. |
No, only writes cause a panic, all read-operations are fine (and return the zero value). To be clear: My point is that you are making an argument-from-consistency. But I disagree with that. Maps and functions and channels and pointers might all be able to be |
Duplicate of #65629 |
Made an issue for Nop and friends: #68947. |
Proposal Details
I'm not sure if this is a bug, or an intended behavior (couldn't find the answer anywhere; looked through package docs, release notes, and GitHub Issues), but as someone who's been using Go for more than a decade, I was really surprised to realize that ranging over nil iterators panics.
E.g. the following code panics:
While ranging over nil slices and maps is allowed:
The map example is the thing that brought me to raise this problem. Normally uninitialized maps are not useful anywhere, and accessing them causes panic, but ranging over them is allowed. Seems inconsistent (and frankly a bit unfair) that doing the same with iterators is not allowed.
So, I'd like to propose to allow ranging over nil iterators in the similar way as ranging over nil slices and maps is allowed. I'd assume this is a backwards-compatible change.
The text was updated successfully, but these errors were encountered: