Search code examples
goreverse-engineering

What exactly does the selectnbrecv function from Go do?


I'm reverse engineering a Go binary and came across the function selectnbrecv. However, I don't understand the documentation. I'll appreciate it if someone can explain to me the context and operation of the function. Thanks!


Solution

  • It is the Go runtime internal implemetaion for non blocking receive from the channel:
    When the channel has any events the selectnbrecv function returns true otherwise returns false (for nil channel returns false): It receives on channel and writes the received data to v (if &v is not nil, in which case received data is ignored.) If no data are available, returns false. Otherwise, if the channel is closed, zeros v and returns true. Otherwise, fills in v with a data and returns true.

    // compiler implements
    //
    //  select {
    //  case v = <-c:
    //      ... foo
    //  default:
    //      ... bar
    //  }
    //
    // as
    //
    //  if selectnbrecv(&v, c) {
    //      ... foo
    //  } else {
    //      ... bar
    //  }
    //
    func selectnbrecv(elem unsafe.Pointer, c *hchan) (selected bool) {
        selected, _ = chanrecv(c, elem, false) // false for non blocking
        return
    }