Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

context: Clarify desired key type #30408

Closed
mcandre opened this issue Feb 26, 2019 · 5 comments
Closed

context: Clarify desired key type #30408

mcandre opened this issue Feb 26, 2019 · 5 comments

Comments

@mcandre
Copy link

mcandre commented Feb 26, 2019

Hi, I am trying to resolve some interesting linter warnings around context key types. For some reason, ordinary strings are being discouraged as context key types, e.g. by golint.

One specific recommendation online is to use interface{} instead. Is this a good idea?

var EmailClientKey interface{} = "email_client"

Could we use the Go type system to make this easier for the user? Perhaps alias interface{} as a ContextKey type, and require in the Context API methods that the keys are passed in with the ContextKey type.

@mvdan
Copy link
Member

mvdan commented Feb 26, 2019

Duplicate of #17826? If you think the documentation is lacking, please point out what is missing.

@bcmills bcmills changed the title Clarify desired context key type context: Clarify desired key type Feb 27, 2019
@bcmills
Copy link
Contributor

bcmills commented Feb 27, 2019

The current documentation says:

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context.

So using a string value is clearly out, even if you assign it to a variable of type interface{}

@bcmills
Copy link
Contributor

bcmills commented Feb 27, 2019

Perhaps alias interface{} as a ContextKey type, and require in the Context API methods that the keys are passed in with the ContextKey type.

Aliasing anything to interface{} makes it exactly as weak as interface{} from a type perspective: anything is assignable to it, so anything can be passed as it.

@bcmills
Copy link
Contributor

bcmills commented Feb 27, 2019

Duplicate of #17826

@bcmills bcmills closed this as completed Feb 27, 2019
@mcandre
Copy link
Author

mcandre commented Mar 2, 2019

In that case, have the compiler reject string keys for context API calls

@bcmills bcmills marked this as a duplicate of #17826 Apr 13, 2019
@golang golang locked and limited conversation to collaborators Apr 12, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants