Search code examples
goforeachcallbackiterationtermination

Should true or false terminate callback iteration?


In some languages it's necessary or cleaner to do iteration by providing a callback function that receives items and returns a boolean that indicates whether to continue or stop the iteration.

Which is the preferred value to indicate desire to stop/continue? Why? What precedents exist?

Example in Go:

func IntSliceEach(sl []int, cb func(i int) (more bool)) (all bool) {
    for _, i := range sl {
        if !cb(i) {
            return false
        }
    }
    return true
}

Solution

  • Which is the preferred value to indicate desire to stop/continue?

    true for continue

    Why?

    Example 1:

    func example(i interface{}) {
        if w, ok := i.(io.Writer); ok {
            // do something with your writer, ok indicates that you can continue
        }
    }
    

    Example 2:

    var sum int = 0
    it := NewIntStatefulIterator(int_data)
    for it.Next() {
        sum += it.Value()
    }
    

    In both cases true (ok) indicates that you should continue. So I assume that it would be way to go in your example.