We have written one program by which we try to find an address of a constant. Is it possible to do it like that?
package main
func main() {
const k = 5
address := &k
}
It gives an error, can anyone tell how can we find the address of a constant?
In short: you can't.
The error message says:
There are limitations on the operand of the address operator
&
. Spec: Address operators:Constants are not listed as addressable, and things that are not listed in the spec as addressable (quoted above) cannot be the operand of the address operator
&
(you can't take the address of them).It is not allowed to take the address of a constant. This is for 2 reasons:
If you need a pointer to a value being equal to that constant, assign it to a variable of which is addressable so you can take its address, e.g.
But know that in Go numeric constants represent values of arbitrary precision and do not overflow. When you assign the value of a constant to a variable, it may not be possible (e.g. the constant may be greater than the max value of the variable's type you're assigning it to - resulting in compile-time error), or it may not be the same (e.g. in case of floating point constants, it may lose precision).
I often hit this problem when creating large, nested JSON objects during unit tests. I might have a structure where all the fields are pointers to strings/ints:
and want to write something like:
When I initialise it, but the language doesn't allow this directly. A quick way to bypass this is to define a function that takes a constant and returns its address:
This works due to the fact that when the constant is passed as a parameter to the function, a copy of the constant is made which means the pointer created in the function does not point to the address of the constant, but to the address of its copy, in the same way as when a constant value is assigned to a
var
. However, using a function to do this makes it more readable/less cumbersome IMO than having to forward declare large blocks of variables.What the constants section does not make very clear: Constants are, unlike variables, not present in the compiled code or running program. They are untyped and will only be in memory once they are assigned to a variable.
As a result, they seem1 to have infinite precision. If you look at this example, you can see that I can assign the constant to a variable without casting it, and the variable will hold as much of the constants precision as it can.
1 As the spec also points out, integers have at least 256 bits, floats at least 256 bits mantissa and 32 bits exponent, and the compiler will throw an error if its internal constructs cannot accurately store a constant.