gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/chans/chan.go (about) 1 package chans 2 3 func AsyncPush[O any](c chan O, o O) { 4 select { 5 case c <- o: 6 default: 7 go func(c chan O) { 8 c <- o 9 }(c) 10 } 11 } 12 13 func TryPush[O any](c chan O, o O) bool { 14 select { 15 case c <- o: 16 return true 17 default: 18 return false 19 } 20 } 21 22 func TryPop[O any](c chan O) (o O, ok bool) { 23 select { 24 case o = <-c: 25 ok = true 26 default: 27 } 28 return 29 } 30 31 func noPanicError(ep *error) { 32 if e := recover(); e != nil { 33 if err, _ := e.(error); err != nil { 34 *ep = err 35 } else { 36 panic(e) 37 } 38 } 39 } 40 41 func NoPanicPush[O any](c chan O, o O) (err error) { 42 defer noPanicError(&err) 43 c <- o 44 return nil 45 } 46 47 func NoPanicTryPush[O any](c chan O, o O) (ok bool, err error) { 48 defer noPanicError(&err) 49 select { 50 case c <- o: 51 return true, nil 52 default: 53 return false, nil 54 } 55 }