Search code examples
go

Is there a shortcut for assigning a variable to a pointer without creating the variable in a separate line first?


If I have a struct like this:

type Message struct {
    Id      int64
    Message string
    ReplyTo *int64
}

And then if I did create an instance of this struct like this:

var m Message
m.Id = 1
m.Message = "foo bar yo"

var replyTo = int64(64)
m.ReplyTo = &replyTo

Then it would work.

But I was wondering if there was a shortcut for the last step?

I tried doing something like:

m.ReplyTo = &int64{64}

But it did not work.


Solution

  • I don't think you can because the value is a primitive and attempting to do it in one shot like the below would be a syntax error. Its attempting to get an address of a value so it wouldn't be possible. At least I am not aware of a way where its possible.

    someInt := &int64(10) // would not compile 
    

    The other alternative you have is to write a function to return a pointer to the primitive like the following:

    func NewIntPointer(value int) *int {
      return &value
    }