node icon indicating copy to clipboard operation
node copied to clipboard

stopping putting context.Context in a struct

Open hydrogen18 opened this issue 4 years ago • 4 comments

Based on the documentation for the context package you shouldn't store a context.Context in a struct, but instead it pass it wherever you need it. I guess this makes some things simpler for GC or other stuff.

We have at least a few places where I know I've done this, so we should sweep through the codebase and eliminate this practice.

hydrogen18 avatar May 27 '21 21:05 hydrogen18

What does it say? Is it a pattern/style recommendation or something related to memory management?

boz avatar May 27 '21 21:05 boz

It isn't specific and doesn't show a clear pitfall, but this is what the docs say

Programs that use Contexts should follow these rules to keep interfaces consistent across packages and enable static analysis tools to check context propagation:

Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx:

hydrogen18 avatar May 27 '21 21:05 hydrogen18

I kinda think it's an over-opinionated comment. Check out where we use it - I'm open to changing it but I don't think we absolutely have to just based on this comment.

boz avatar May 27 '21 21:05 boz

i think comment means there should be only one reference to the context object and passing it through argument is one of patterns. using it through argument makes sense for cases like nested calls, especially when callee needs context.WithValue|Timeout, http handler is good example of it. using context as a struct values makes sense when context object does not leave scope. we might continue using both just have to not mix them as it is easy to pass wrong context object when there are a few of them in the scope

troian avatar May 28 '21 06:05 troian