Skip to content

Commit

Permalink
feat: super 包新增 TryReadChannel、TryReadChannelByHandler 函数用于对 channel …
Browse files Browse the repository at this point in the history
…尝试写入
  • Loading branch information
kercylan98 committed Jan 19, 2024
1 parent 756f823 commit 959abff
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions utils/super/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,25 @@ func TryWriteChannelByHandler[T any](ch chan<- T, data T, handler func()) {
handler()
}
}

// TryReadChannel 尝试读取 channel,如果 channel 无法读取则忽略,返回是否读取成功
// - 无法读取的情况包括:channel 已空、channel 已关闭
func TryReadChannel[T any](ch <-chan T) (v T, suc bool) {
select {
case data := <-ch:
return data, true
default:
return v, false
}
}

// TryReadChannelByHandler 尝试读取 channel,如果 channel 无法读取则执行 handler
// - 无法读取的情况包括:channel 已空、channel 已关闭
func TryReadChannelByHandler[T any](ch <-chan T, handler func(ch <-chan T) T) (v T) {
select {
case data := <-ch:
return data
default:
return handler(ch)
}
}

0 comments on commit 959abff

Please sign in to comment.