-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: Go 2: make constants and literals addressable #28681
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
Comments
|
This is #19966, which was closed as a special case of the more general #9097 (see e.g. #9097 (comment)). |
My bad, I should have included real-world examples. The main advantage is brevity. Especially when working with constructs that have nullables (ie JSON) structures need to have
Initializing these structs that use
Now imagine calling that function but using all of the possible parameters AWS realized that this was a problem, so they provided a "solution":
So then our function call would look like:
The repetition of
That is fair I guess. Having it shown over two lines is good to show that there is extra cost. I'd personally call that a micro-optimization though. After all
Again, my AWS example is what I'm trying to avoid. |
I couldn't find any proposals for this, but it seems like something that someone would have already proposed. So I apologize if this is a duplicate.
This proposal is to make constants, and some expressions, addressable. It is quite simple so I will keep it that way.
How it works
A pointer to a constant expression would result in a new pointer to the value the expression represents.
This is the same way that pointers to pointers to composite literals work, so I don't personally think it's unintuitive or anything. The only slightly unintuitive part is that
&namedConstant == &namedConstant
evaluates tofalse
, although I don't personally find that unintuitive.Example:
Modifying constant pointers
Modifying a constant pointer should not panic. The value at the pointer would still be modified, because the pointer doesn't really point to
five
, it points to a value that the calling function doesn't have access to anyway. This is exactly how pointers to composite literals work.Modifying constant pointers (with read-only types)
If we had read-only types, the resulting pointer would be a read-only pointer. So ideally our
fmt.Scanf
lines from the previous example would not even compile.The text was updated successfully, but these errors were encountered: