Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to non-composite literal

Tags:

go

Is there an established pattern for getting pointers to non-composite literals?

x := 5
y := &x

The above code works, but is awfully verbose.

like image 703
Chris Pfohl Avatar asked Jul 11 '13 20:07

Chris Pfohl


1 Answers

If I understand correctly that the only point of x is to allocate the int, I recommend something even more "verbose":

y := new(int)
*y = 5

I don't see getting it any shorter than what you have. Since the & operator requires its operand to be either addressable or a composite literal, you're either stuck doing what you're doing to get something addressable, or you can do what I suggest and avoid the & altogether.

like image 109
Darshan Rivka Whittle Avatar answered Sep 28 '22 02:09

Darshan Rivka Whittle