2 ms·
> Usually you do this via defer. I agree this is usually done by defer, but you probably should not do it that way unless your code is very simple. Consider a
by morelisp 7y ago
> Usually you do this via defer.
I agree this is usually done by defer, but you probably should not do it that way unless your code is very simple. Consider a function body which I've seen variants of many times:
ctx, cancel = context.WithTimeout(pctx, timeout)
defer cancel()
if resp, err := do(ctx, req); err == nil {
process(resp)
}
return err
Safe yes, but optimal? process doesn't use the context, and may take longer than the timeout. The context will continue running, with some associated resource cost (at the very least, the context's goroutine and timer). A minimal change is:
ctx, cancel = context.WithTimeout(pctx, timeout)
resp, err := do(ctx, req)
cancel()
if err == nil {
process(resp)
}
return err
Which disposes of those resources much earlier.
(Depending on your Go compiler version there is also a potential cost associated simply with using defer; this is independent of that.)