2

I have Go function, and I want to dereference the first value to store in a pointer.

E.g.:

func foo() (int64, error) {...}
var A *int64
var err error
A, err = &foo()

Is this possible, or do I have to copy the (in my case very large) return value?

JustinHK
  • 758
  • 1
  • 6
  • 19
  • 1
    Possible duplicate of [How to get the pointer of return value from function call?](http://stackoverflow.com/questions/30744965/how-to-get-the-pointer-of-return-value-from-function-call) Also related: [How can I store reference to the result of an operation in Go](http://stackoverflow.com/questions/34197248/how-can-i-store-reference-to-the-result-of-an-operation-in-go) – icza May 02 '16 at 14:20
  • I had assumed that I could do it a for a single-value function call, so I didn't even see that; I guess ultimately this means the question is moot. – JustinHK May 02 '16 at 15:41

1 Answers1

6

You can't do that. The address operator & cannot be applied on function calls.

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.

What you should do is change your function to return a pointer in the first place, if it does matter.

icza
  • 389,944
  • 63
  • 907
  • 827