github.com/searKing/golang/go@v1.2.74/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 (
     8  	"golang.org/x/exp/slices"
     9  )
    10  
    11  // FirstFunc returns the first item from the slice satisfying f(c), or zero if none do.
    12  func FirstFunc[S ~[]E, E any](s S, f func(E) bool) (e E, ok bool) {
    13  	var zeroE E
    14  	i := slices.IndexFunc(s, f)
    15  	if i == -1 {
    16  		return zeroE, false
    17  	}
    18  	return s[i], true
    19  }
    20  
    21  // FirstOrZero returns the first non-zero item from the slice, or zero if none do.
    22  func FirstOrZero[E comparable](s ...E) E {
    23  	var zeroE E
    24  	return FirstOrZeroFunc(s, func(e E) bool { return e != zeroE })
    25  }
    26  
    27  // FirstOrZeroFunc returns the first item from the slice satisfying f(c), or zero if none do.
    28  func FirstOrZeroFunc[S ~[]E, E any](s S, f func(E) bool) E {
    29  	e, _ := FirstFunc(s, f)
    30  	return e
    31  }