前两天,在滴滴面试中,被问到select中实现优先级问题,但是知道select中事件是随机触发的,没有想到如何实现,面试官告知 可以使用default实现,自己想想golang文档中有说过,自己读书不认真。今天又发现开发NSQ中就有使用,特此记录。

for msg := range c.incomingMsgChan {
    select {
    case c.memoryMsgChan <- msg:
    default:
        err := WriteMessageToBackend(&msgBuf, msg, c.backend)
        if err != nil {
            // ... handle errors ...
        }
    }
}
Taking advantage of Go’s select statement allows this functionality to be expressed in just a few lines of code: the default case above only executes if memoryMsgChan is full.