Skip to content

Commit

Permalink
新增:FirstAddr方法,返回指针Item元素
Browse files Browse the repository at this point in the history
  • Loading branch information
steden committed Mar 3, 2024
1 parent e901de2 commit b83a908
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions enumerable.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@ func (receiver Enumerable[T]) First() T {
return t
}

// First 查找符合条件的第一个指针元素
func (receiver Enumerable[T]) FirstAddr() *T {
if receiver.lock == nil {
return nil
}

receiver.lock.RLock()
defer receiver.lock.RUnlock()

if len(*receiver.source) > 0 {
return &(*receiver.source)[0]
}
return nil
}

// Last 集合最后一个元素
func (receiver Enumerable[T]) Last() T {
if receiver.lock == nil {
Expand Down
14 changes: 14 additions & 0 deletions test/enumerable_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,20 @@ func Test_enumerable_First(t *testing.T) {
assert.Equal(t, 1, lst.First())
}

func Test_enumerable_FirstAddr(t *testing.T) {
type Name struct {
Age int
}
lst := collections.NewList[Name](Name{Age: 8})
assert.Equal(t, 8, lst.First().Age)

item := lst.FirstAddr()
item.Age = 99

assert.Equal(t, 99, lst.First().Age)
assert.Equal(t, 99, lst.FirstAddr().Age)
}

func Test_enumerable_Last(t *testing.T) {
lst := collections.NewList[int](1, 2, 3, 4, 5, 6)
assert.Equal(t, lst.Last(), 6)
Expand Down

0 comments on commit b83a908

Please sign in to comment.