Hacker News new | ask | show | jobs
by eadmund 1511 days ago
> Fun fact: that func has a hidden bug, if one should be pedantic. Can you spot it?

Are you referring to the fact that the timer is still hanging around? Would this be the most-correct version?

    func sleepCtx(ctx context.Context, delay time.Duration) {
            t := time.NewTimer(delay)
            defer func() {
                    if !t.Stop() {
                            <-t.C
                    }
            }()
            select {
            case <-ctx.Done():
            case <-t.C:
            }
    }
1 comments

[Weird, I remember already replying to this comment.]

Yes that's what I was thinking of :)

I'm a bit unsure what's the value in draining the channel (which is internal to this func), given that Go should garbage collect channel (and in this case perhaps even some escape analysis).

EDIT: Ah they aren't just closing the channel, but sending a time.Time. That makes sense, the timer wouldn't have anyone to send to if it's unbuffered.