-
Notifications
You must be signed in to change notification settings - Fork 17.6k
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
proposal: Add constant error #17226
Comments
we can't define errors.Error as string, because then
anyone can assign a (untyped) string to errors.Error,
and that's the reason why errors.New returns a struct
wrapping a string.
|
Maybe some people need this. |
This isn't happening for Go 1, so kicking this into the Go2 abyss. |
If it's a Go2 item, then I'd suggest we change it to request proper
constant support for more types (e.g. C++'s constexpr)
|
We can discuss later. |
Faced use case with context keys: ctx.Value("key") // cause allocation for convert string "key" to interface{} Global variable do this allocation once: var CONTEXT_KEY interface{} = "key" // for now using var instead of constx
...
ctx.Value(CONTEXT_KEY) |
Do not use strings as context keys. See #17302 and the new golint rule. |
We used to use exactly the implementation of errors.Error given in the proposal. We moved away from it so that if two different packages used errors.New("msg") for different things, the two would not accidentally be equal.
You probably don't need to guarantee it. The standard library exports many errors and makes no such guarantee, and programs work fine, because programs can mostly be trusted not to modify those errors (for example, they don't reassign io.EOF), and those programs that can't be trusted deserve to break badly anyway. If you really needed to guarantee this, then instead of exporting the variable you could instead export a function that returns it:
Then no one can modify the definition in use in your program. |
The origin of the problem
Here is an exmaple:
I need export the
ErrNotFound
, butErrNotFound
need to be guaranteed not to be modified.Proposal
So I proposal add following code in
errors
package:Through doing this, I can define
ErrNotFound
like this:The text was updated successfully, but these errors were encountered: