github.com/searKing/golang/go@v1.2.117/exp/slices/first.go (about) 1 // Copyright 2022 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slices 6 7 import "slices" 8 9 // FirstFunc returns the first item from the slice satisfying f(c), or zero if none do. 10 func FirstFunc[S ~[]E, E any](s S, f func(E) bool) (e E, ok bool) { 11 var zeroE E 12 i := slices.IndexFunc(s, f) 13 if i == -1 { 14 return zeroE, false 15 } 16 return s[i], true 17 } 18 19 // FirstOrZero returns the first non-zero item from the slice, or zero if none do. 20 func FirstOrZero[E comparable](s ...E) E { 21 var zeroE E 22 return FirstOrZeroFunc(s, func(e E) bool { return e != zeroE }) 23 } 24 25 // FirstOrZeroFunc returns the first item from the slice satisfying f(c), or zero if none do. 26 func FirstOrZeroFunc[S ~[]E, E any](s S, f func(E) bool) E { 27 e, _ := FirstFunc(s, f) 28 return e 29 }