Last active
August 1, 2019 08:13
-
-
Save davidmz/11190975 to your computer and use it in GitHub Desktop.
[Безопасная запись в канал] Если канал открыт, то производится обычная (возможно блокирующая) запись. Если канал закрыт, то функция сразу и без паники возвращает управление. По возвращаемому функцией значению можно определить, была ли произведена запись.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Если канал открыт, то производится обычная (возможно блокирующая) запись. | |
// Если канал закрыт, то функция сразу и без паники возвращает управление. | |
// По возвращаемому функцией значению можно определить, была ли произведена запись. | |
func TrySend(it interface{}, itChan interface{}) (sent bool) { | |
itVal := reflect.ValueOf(it) | |
itChanVal := reflect.ValueOf(itChan) | |
itChanValT := itChanVal.Type() | |
if itChanValT.Kind() != reflect.Chan { | |
panic("Non-channel type") | |
} | |
if itChanValT.ChanDir()&reflect.SendDir == 0 { | |
panic("Invalid channel direction") | |
} | |
if itChanValT.Elem() != itVal.Type() { | |
panic("Types don't match") | |
} | |
func() { | |
defer func() { sent = (recover() == nil) }() | |
itChanVal.Send(itVal) | |
}() | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment