如何在结构初始化器中使用指针类型?

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

How to use pointer type in struct initializer?

问题

我无法弄清楚当结构字段是一个数字类型的引用类型别名时如何初始化它:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. type Nint64 *int64
  7. type MyStruct struct {
  8. Value Nint64
  9. }
  10. func main() {
  11. data, _ := json.Marshal(&MyStruct{ Value : ?? 10 ?? })
  12. fmt.Println(string(data))
  13. }
英文:

I cannot figure out how to initialize structure field when it is a reference type alias of the one of the number types:

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. type Nint64 *int64
  7. type MyStruct struct {
  8. Value Nint64
  9. }
  10. func main() {
  11. data, _ := json.Marshal(&MyStruct{ Value : ?? 10 ?? })
  12. fmt.Println(string(data))
  13. }

答案1

得分: 1

你可以在这里添加一个额外的步骤 playground

  1. func NewMyStruct(i int64) *MyStruct {
  2. return &MyStruct{&i}
  3. }
  4. func main() {
  5. i := int64(10)
  6. data, _ := json.Marshal(&MyStruct{Value: Nint64(&i)})
  7. fmt.Println(string(data))
  8. //或者这样
  9. data, _ = json.Marshal(NewMyStruct(20))
  10. fmt.Println(string(data))
  11. }
英文:

You can't, you will have to add an extra step <kbd>playground</kbd>:

  1. func NewMyStruct(i int64) *MyStruct {
  2. return &amp;MyStruct{&amp;i}
  3. }
  4. func main() {
  5. i := int64(10)
  6. data, _ := json.Marshal(&amp;MyStruct{Value: Nint64(&amp;i)})
  7. fmt.Println(string(data))
  8. //or this
  9. data, _ = json.Marshal(NewMyStruct(20))
  10. fmt.Println(string(data))
  11. }

答案2

得分: 1

我不认为你想引用 int64 的地址...

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type Nint64 int64
  7. type MyStruct struct {
  8. Value Nint64
  9. }
  10. func main() {
  11. data, _ := json.Marshal(&MyStruct{Value: Nint64(10)})
  12. fmt.Println(string(data))
  13. }

http://play.golang.org/p/xafMLb_c73

英文:

I don't think you want to reference to the address of an int64 ...

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;fmt&quot;
  5. )
  6. type Nint64 int64
  7. type MyStruct struct {
  8. Value Nint64
  9. }
  10. func main() {
  11. data, _ := json.Marshal(&amp;MyStruct{Value: Nint64(10)})
  12. fmt.Println(string(data))
  13. }

http://play.golang.org/p/xafMLb_c73

huangapple
  • 本文由 发表于 2014年7月9日 10:53:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/24644676.html
匿名

发表评论

匿名网友

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

确定