From 959abff85f4cbf0c4c81b586317e39bf3dee3a80 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 19 Jan 2024 17:15:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20super=20=E5=8C=85=E6=96=B0=E5=A2=9E=20T?= =?UTF-8?q?ryReadChannel=E3=80=81TryReadChannelByHandler=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E7=94=A8=E4=BA=8E=E5=AF=B9=20channel=20=E5=B0=9D?= =?UTF-8?q?=E8=AF=95=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/super/channel.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/utils/super/channel.go b/utils/super/channel.go index 242510cc..3d3e24b7 100644 --- a/utils/super/channel.go +++ b/utils/super/channel.go @@ -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) + } +}