有没有一种快捷方式可以在不先创建变量的情况下将变量分配给指针?

huangapple go评论78阅读模式
英文:

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

问题

如果我有这样一个结构体:

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

然后如果我像这样创建一个结构体的实例:

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

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

那么它会起作用。

但我想知道是否有一个快捷方式来完成最后一步?

我尝试了这样的操作:

m.ReplyTo = &int64{64}

但它不起作用。

英文:

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.

答案1

得分: 2

我不认为你可以这样做,因为该值是一个原始值,尝试像下面这样一次性操作会导致语法错误。它试图获取一个的地址,所以这是不可能的。至少我不知道有一种可以实现的方式。

someInt := &int64(10) // 不会编译通过

你还有另一种选择,可以编写一个函数来返回指向原始值的指针,如下所示:

func NewIntPointer(value int) *int {
  return &value
}
英文:

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
}

答案2

得分: 1

获取int指针的一个巧妙方法,而不需要创建新的变量。

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

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

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

huangapple
  • 本文由 发表于 2015年10月13日 05:53:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/33090833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定