How to get the pointer of return value from function call?

Solution 1:

The probably unsatisfying answer is "you can't do it because the spec says so." The spec says that to use & on something it has to be addressable or a compound literal, and to be addressable it has to be "a variable, pointer indirection, or slice indexing operation; or a a field selector of an addressable struct operand; or an array indexing operation of an addressable array." Function calls and method calls are definitely not on the list.

Practically speaking, it's probably because the return value of a function may not have a usable address; it may be in a register (in which case it's definitely not addressable) or on the stack (in which case it has an address, but one that won't be valid if it's put in a pointer that escapes the current scope. To guarantee addressability, Go would have to do pretty much the exact equivalent of assigning it to a variable. But Go is the kind of language that figures that if it's going to allocate storage for a variable it's going to be because you said to, not because the compiler magically decided to. So it doesn't make the result of a function addressable.

Or I could be over-thinking it and they simply didn't want to have a special case for functions that return one value versus functions that return multiple :)

Solution 2:

You can't directly take the address of a function call (or more precisely the return value(s) of the function) as described by hobbs.

There is another way but it is ugly:

p := &[]time.Time{time.Now()}[0]
fmt.Printf("%T %p\n%v", p, p, *p)

Output (Go Playground):

*time.Time 0x10438180
2009-11-10 23:00:00 +0000 UTC

What happens here is a struct is created with a literal, containing one element (the return value of time.Now()), the slice is indexed (0th element) and the address of the 0th element is taken.

So rather just use a local variable:

t := time.Now()
p := &t

Or a helper function:

func ptr(t time.Time) *time.Time {
    return &t
}

p := ptr(time.Now())

Which can also be a one-liner anonymous function:

p := func() *time.Time { t := time.Now(); return &t }()

Or as an alternative:

p := func(t time.Time) *time.Time { return &t }(time.Now())

For even more alternatives, see:

How do I do a literal *int64 in Go?

Also see related question: How can I store reference to the result of an operation in Go?