mirror of
https://github.com/samber/lo.git
synced 2026-04-22 23:47:11 +08:00
2.1 KiB
2.1 KiB
name, slug, sourceRef, category, subCategory, signatures, playUrl, variantHelpers, similarHelpers, position
| name | slug | sourceRef | category | subCategory | signatures | playUrl | variantHelpers | similarHelpers | position | |||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| NthOrEmpty | nthorempty | it/find.go#L444 | it | find |
|
https://go.dev/play/p/3UoHL7-zt |
|
|
600 |
Returns the element at index nth of collection. If nth is out of bounds, returns the zero value (empty value) for that type.
Will iterate n times through the sequence.
Examples:
// Get element at specific index
numbers := it.Slice([]int{5, 2, 8, 1, 9})
element := it.NthOrEmpty(numbers, 2)
// element: 8
// Get first element (index 0)
first := it.NthOrEmpty(numbers, 0)
// first: 5
// Get last element
last := it.NthOrEmpty(numbers, 4)
// last: 9
// Out of bounds - negative, returns zero value
element := it.NthOrEmpty(numbers, -1)
// element: 0 (zero value for int)
// Out of bounds - too large, returns zero value
element := it.NthOrEmpty(numbers, 10)
// element: 0 (zero value for int)
// With strings
words := it.Slice([]string{"hello", "world", "go", "lang"})
element := it.NthOrEmpty(words, 1)
// element: "world"
// Out of bounds with string - returns empty string
element := it.NthOrEmpty(words, 10)
// element: "" (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},
})
element := it.NthOrEmpty(people, 1)
// element: {Name: "Bob", Age: 25}
// Out of bounds with struct - returns zero value
element := it.NthOrEmpty(people, 5)
// element: {Name: "", Age: 0} (zero value for Person)
// With pointers - returns nil when out of bounds
values := it.Slice([]*string{ptr("hello"), ptr("world")})
element := it.NthOrEmpty(values, 1)
// element: pointer to "world"
// Out of bounds with pointer - returns nil
element := it.NthOrEmpty(values, 5)
// element: nil (zero value for *string)
// With different integer types
numbers := it.Slice([]int{1, 2, 3, 4, 5})
element := it.NthOrEmpty(numbers, int8(3))
// element: 4