Find address of constant in go

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:

type Obj struct {
    Prop1  *string
    Prop2  *int
    Status *string
}

and want to write something like:

obj := Obj{
    Prop1:  &"a string property",
    Prop2:  &5,
    Status: &statuses.Awesome,
}

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:

 s := func(s string) *string { return &s }
 i := func(i int) *int { return &i }

 obj := Obj{
    Prop1:  s("a string property"),
    Prop2:  i(5),
    Status: s(statuses.Awesome)
}

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.

The AWS SDK uses this technique. I now find myself regularly adding a package to my projects that looks something like:

package ref

import "time"

func Bool(i bool) *bool {
    return &i
}

func Int(i int) *int {
    return &i
}

func Int64(i int64) *int64 {
    return &i
}

func String(i string) *string {
    return &i
}

func Duration(i time.Duration) *time.Duration {
    return &i
}

func Strings(ss []string) []*string {
    r := make([]*string, len(ss))
    for i := range ss {
        r[i] = &ss[i]
    }
    return r
}

Which I call in the following way:

func (t: Target) assignString(to string, value string) {
    if to == tags.AuthorityId {
        t.authorityId = ref.String(value)
    }
    // ...
}

You can also add a deref package, though I have generally found this to be less useful:

package deref

func String(s *string, d string) string {
    if s != nil { return *s }
    return d
}

// more derefs here.

EDIT April 2022:

With the release of go 1.18, it's now possible to define a single method to handle all conversions from constants into pointers:

package ref

func Of[E any](e E) *E {
    return &e
}

In short: you can't.

The error message says:

cannot take the address of k

There are limitations on the operand of the address operator &. Spec: Address operators:

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal. If the evaluation of x would cause a run-time panic, then the evaluation of &x does too.

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:

  1. A constant may not have an address at all.
  2. And even if a constant value is stored in memory at runtime, this is to help the runtime to keep constants that: constant. If you could take the address of a constant value, you could assign the address (pointer) to a variable and you could change that (the pointed value, the value of the constant). Robert Griesemer (one of Go's authors) wrote why it's not allowed to take a string literal's address: "If you could take the address of a string constant, you could call a function [that assigns to the pointed value resulting in] possibly strange effects - you certainly wouldn't want the literal string constant to change." (source)

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.

func main() {
    const k = 5
    v := k
    address := &v // This is allowed
}

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).