5

Given a struct that looks like

type foo struct {
 i *int
}

if I want to set i to 1, I must

throwAway := 1
instance := foo { i: &throwAway }

Is there any way to do this in a single line without having to give my new i value it's own name (in this case throwaway)?

MushinNoShin
  • 4,695
  • 2
  • 32
  • 46
  • I recommend to check [this extensive answer](https://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in-go/30716481#answer-30716481) to a very similar question. – Arnau Jan 22 '21 at 14:25

2 Answers2

10

As pointed in the mailing list, you can just do this:

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

and then

instance := foo { i: intPtr(1) }

if you have to do it often. intPtr gets inlined (see go build -gcflags '-m' output), so it should have next to no performance penalty.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119
5

No this is not possible to do in one line.

Volker
  • 40,468
  • 7
  • 81
  • 87
  • 2
    Gross. Any thoughts as to why not? Is it just too difficult to implement to remove an occasionally noisy line? – MushinNoShin Apr 08 '15 at 16:54
  • 6
    @MushinNoShin: a pointer is the address of some thing, so you need that *thing*. – maerics Apr 08 '15 at 16:57
  • 1
    @maerics: that was already understood, this was asking if there's any convenient ways to automatically do the memory allocation in the background and keep the unnecessary noise out of my code. See the accepted answer. – MushinNoShin Apr 08 '15 at 17:26
  • 1
    Pointers to ints are not that common and pointers to literal ints are very uncommon, so why bother with syntactical sugar? – Volker Apr 08 '15 at 20:17
  • @Volker you should take a look at `aws-sdk-golang`, they've got pointers to literal ints for days. – Civilian May 04 '15 at 22:19