github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/iterutil/iterutil.go (about) 1 // Copyright 2020 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package iterutil 12 13 import "github.com/cockroachdb/errors" 14 15 var errStopIteration = errors.New("stop iteration") 16 17 // StopIteration returns a sentinel error that indicates stopping the iteration. 18 // 19 // This error should not be propagated further, i.e., if a closure returns 20 // this error, the loop should break returning nil error. For example: 21 // 22 // f := func(i int) error { 23 // if i == 10 { 24 // return iterutil.StopIteration() 25 // } 26 // return nil 27 // } 28 // 29 // for i := range slice { 30 // if err := f(i); err != nil { 31 // return iterutil.Map(err) 32 // } 33 // // continue when nil error 34 // } 35 func StopIteration() error { return errStopIteration } 36 37 // Map the nil if it is StopIteration, or keep the error otherwise 38 func Map(err error) error { 39 if errors.Is(err, errStopIteration) { 40 return nil 41 } 42 return err 43 }