mirror of
https://github.com/samber/lo.git
synced 2026-04-22 15:37:14 +08:00
feat(channel): adding lo.SafeClose()
This commit is contained in:
+14
@@ -304,3 +304,17 @@ func FanOut[T any](count int, channelsBufferCap int, upstream <-chan T) []<-chan
|
||||
|
||||
return channelsToReadOnly(downstreams)
|
||||
}
|
||||
|
||||
// SafeClose protects against double-close panic.
|
||||
// Returns true on first close, only.
|
||||
// May be equivalent to calling `sync.Once{}.Do(func() { close(ch) })`.`
|
||||
func SafeClose[T any](ch chan<- T) (justClosed bool) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
justClosed = false
|
||||
}
|
||||
}()
|
||||
|
||||
close(ch) // may panic
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -388,3 +388,13 @@ func TestFanOut(t *testing.T) {
|
||||
is.Equal(0, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeClose(t *testing.T) {
|
||||
t.Parallel()
|
||||
is := assert.New(t)
|
||||
|
||||
ch := make(chan int)
|
||||
|
||||
is.True(SafeClose(ch))
|
||||
is.False(SafeClose(ch))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user