3 ms·
Not sure I understand the typing issue. The standard pattern is to provide an x.Context(ctx, ...) and an x.FromContext(ctx), and those are the only two function
by tommiegannert 3y ago
Not sure I understand the typing issue. The standard pattern is to provide an x.Context(ctx, ...) and an x.FromContext(ctx), and those are the only two functions that know about the context key, and they do the type-casting. Since they are the only functions knowing the context key (the key is often a pointer to an unexported variable), you are guaranteed type-safety as long as there is no unsafe code that can pretend-inject the key.
https://cs.opensource.google/go/go/+/refs/tags/go1.20.5:src/context/context.go;l=343;drc=61f5a672edd6cce959a47e20dcfb59eaaa5ebd56 https://cs.opensource.google/go/go/+/refs/tags/go1.20.5:src/...
- collinvandyck76 3y agoWhen people mention type safety in this context, they are talking about compiler guarantees. Application code that uses type assertions will never be "type safe" in the way that a compiler can ensure. So while you're correct that if the application code that does the type checking is bug free then the type safety is implied, but is not certain in all cases.
- adamwk 3y agoSure but the interface is typesafe and usually that’s good enough. The two methods of the API (NewContext and FromContext) are typesafe from the perspective of the user.
- ilyt 3y agoWe're talking about context variables which are of type any so you need to check them runtime.
- yencabulator 3y agoThe guarantee you don't get is that foo.FromContext always succeeds. If *Foo was a struct field of your receiver or an argument to the function, the function would be guaranteed to have access to a *Foo.