Alex
Alex

Reputation: 6109

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.

Upvotes: 3

Views: 1802

Answers (4)

Eleandro Duzentos
Eleandro Duzentos

Reputation: 1568

Although there is an answer marked as accepted, I will leave here an alternative:

User{
  Name: func(s string) *string { return &s }("John Doe")
}

Looks weird, but works and doesn't require you to declare to a separate line.

Upvotes: 0

Dharma Bellamkonda
Dharma Bellamkonda

Reputation: 688

In Go 1.18+ you can create a generic function:

func Ptr[T any](v T) *T {
    return &v
}

Usage:

m.ReplyTo = Ptr(int64(64))

Go Playground example

Upvotes: 0

yanss
yanss

Reputation: 144

A tricky way to get int pointer without create new variable.

someIntPtr := &[]int64{10}[0]

Upvotes: 0

Will C
Will C

Reputation: 1794

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
}

Upvotes: 2

Related Questions