Files
lo/docs/data/it-firstorempty.md
T
2025-10-08 19:35:53 +02:00

1.2 KiB

name, slug, sourceRef, category, subCategory, signatures, playUrl, variantHelpers, similarHelpers, position
name slug sourceRef category subCategory signatures playUrl variantHelpers similarHelpers position
FirstOrEmpty firstorempty it/find.go#L370 it find
func FirstOrEmpty[T any](collection iter.Seq[T]) T
https://go.dev/play/p/6NhAE0-zm
it#find#firstorempty
core#slice#firstorempty
540

Returns the first element of a collection or zero value if empty.

Will iterate at most once.

Examples:

// Get the first element or zero value
numbers := it.Slice([]int{5, 2, 8, 1, 9})
first := it.FirstOrEmpty(numbers)
// first: 5

// With empty collection
empty := it.Slice([]int{})
first := it.FirstOrEmpty(empty)
// first: 0 (zero value for int)

// With strings
words := it.Slice([]string{"hello", "world", "go"})
first := it.FirstOrEmpty(words)
// first: "hello"

emptyWords := it.Slice([]string{})
first := it.FirstOrEmpty(emptyWords)
// first: "" (zero value for string)

// With structs
type Person struct {
    Name string
    Age  int
}
people := it.Slice([]Person{
    {Name: "Alice", Age: 30},
    {Name: "Bob", Age: 25},
})
first := it.FirstOrEmpty(people)
// first: {Name: "Alice", Age: 30}

emptyPeople := it.Slice([]Person{})
first := it.FirstOrEmpty(emptyPeople)
// first: {Name: "", Age: 0} (zero value for Person)