3 ms·
Mostly I think of contexts as a way of helping you to deal with the fact that something might initiate some work but that you can’t necessarily guarantee that y
by neilalexander 6y ago
Mostly I think of contexts as a way of helping you to deal with the fact that something might initiate some work but that you can’t necessarily guarantee that you’ll be given enough time to complete it. This might be because there’s a time limit/deadline or because some other condition can be cancelled. This is useful particularly in places where you are dealing with clients/servers over a network.
An example of this is accepting an HTTP request from a client and then creating a response to that request. Ultimately, the client can ultimately give up waiting at any time and disconnect, so being given a request context allows you to deal with this situation - you can check if the context is cancelled at any time and abort whatever expensive operation you were midway through doing or about to do.
Some internal packages, such as net/http and database/sql, accept contexts as a means of avoiding unnecessary work - they will just “no op” if the context has been cancelled by that point, or they may add some new information to the context and pass it downward.
You can also check yourself if a context has been cancelled and you can even use the Done() function to break out of a “select” block early.
Another important detail is that contexts are always limited by their parent context. If the parent gets cancelled, so will any child contexts (such as those created using WithTimeout or WithCancellation).