top | item 39316731

(no title)

swdunlop | 2 years ago

I think of contexts as being Go's answer to dynamic variables in earlier languages, like Lisp, and less like thread local storage (like Pthreads). Much like how Go works with errors, explicit is favored over implicit -- being able to see the context pass through, and whether a function expects a context, tells you a lot about the function you are about to call.

If a function does not take a context, you know it probably cannot be interrupted, just like when a function does not return an error, you know it should not fail. In my work projects, this is also a cue that the function does not do any logging since we always carry a zerolog.Logger in our contexts enriched with trace information about the request and handler.

This also makes life easier for me as a reviewer -- I can see the context passing, I can spot when there is a bad pattern, like retaining a context, or failing to handle an error. It does not require me to maintain a detailed mental map of which functions employ dynamic variables or can throw exceptions.

discuss

order

No comments yet.