3 ms·
The Context package is tricky to use correctly. I got bit because I designed an API that assumed you could embed a Context within a larger struct. Because it's
by mperham 6y ago
The Context package is tricky to use correctly. I got bit because I designed an API that assumed you could embed a Context within a larger struct. Because it's immutable you can't and have to pass it as a value everywhere. It wasn't fun having to break backwards compatibility to fix that mistake.
- AlexCoventry 6y agoNot sure what you mean by "embed a Context within a larger struct." It's certainly possible to have a struct field of type context.Context.
- sagichmal 6y agoPossible, but usually a bad idea.
- mperham 6y agoI didn’t say it wasn’t possible, I meant could as in “safe to do so”. Read the package docs, it explicitly says not to do that.
- morelisp 6y agoIt says not to, but the reason is because you will probably not handle context semantics correctly, not because it inherently breaks anything. If the object you embed the context in has all the properties of a context (short-lived, request-scoped, passed to every function that needs to handle it, and provides a way to create a nested context) then embedding the context is at worst unidiomatic. This is how http.Request did it to preserve backwards-compatibility; http.Handler usage was too pervasive to ever change its signature.