mirror of
https://github.com/samber/lo.git
synced 2026-04-22 23:47:11 +08:00
1.5 KiB
1.5 KiB
name, slug, sourceRef, category, subCategory, signatures, playUrl, variantHelpers, similarHelpers, position
| name | slug | sourceRef | category | subCategory | signatures | playUrl | variantHelpers | similarHelpers | position | |||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| FirstOr | firstor | it/find.go#L377 | it | find |
|
https://go.dev/play/p/7OiBF1-zn |
|
|
550 |
Returns the first element of a collection or the fallback value if empty.
Will iterate at most once.
Examples:
// Get the first element or fallback value
numbers := it.Slice([]int{5, 2, 8, 1, 9})
first := it.FirstOr(numbers, 42)
// first: 5
// With empty collection
empty := it.Slice([]int{})
first := it.FirstOr(empty, 42)
// first: 42 (fallback value)
// With strings
words := it.Slice([]string{"hello", "world", "go"})
first := it.FirstOr(words, "fallback")
// first: "hello"
emptyWords := it.Slice([]string{})
first := it.FirstOr(emptyWords, "fallback")
// first: "fallback"
// With structs
type Person struct {
Name string
Age int
}
people := it.Slice([]Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
})
first := it.FirstOr(people, Person{Name: "Default", Age: 0})
// first: {Name: "Alice", Age: 30}
emptyPeople := it.Slice([]Person{})
first := it.FirstOr(emptyPeople, Person{Name: "Default", Age: 0})
// first: {Name: "Default", Age: 0} (fallback value)
// Using with pointers
pointers := it.Slice([]*int{ptr(5), ptr(10), ptr(15)})
first := it.FirstOr(pointers, nil)
// first: pointer to 5
emptyPointers := it.Slice([]*int{})
first := it.FirstOr(emptyPointers, nil)
// first: nil (fallback value)