google / starlark-go

Starlark in Go: the Starlark configuration language, implemented in Go
BSD 3-Clause "New" or "Revised" License
2.3k stars 209 forks source link

question: Can Done() be called before Interator is has finished? #331

Closed nemith closed 3 years ago

nemith commented 3 years ago

I am implementing an iterator that reads from a channel and I want to make sure that the go routine is completed. Is there ever a case were Done() would be called before finishing the iterator (i.e Next() returns false)?

https://pkg.go.dev/go.starlark.net/starlark#Iterator

alandonovan commented 3 years ago

Yes, the client of an iterator is under no obligation to read to the end, so in a loop such as this:

iter := iterable.Iterator()
defer iter.Done()
var x Value
for iter.Next(&x) {
    ...body...
}

if the body contains a break statement, Done will be called without Next ever having returned false.

However, the client is obliged to call Done, so you could cancel your goroutine there.