JustinHK
JustinHK

Reputation: 768

Dereferencing the first return value in go

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?

Upvotes: 2

Views: 1595

Answers (1)

icza
icza

Reputation: 417462

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.

Upvotes: 6

Related Questions