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

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

How to use pointer type in struct initializer?

问题

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

package main

import (
  "fmt"
  "encoding/json"
)

type Nint64 *int64

type MyStruct struct {
   Value Nint64
}

func main() {
  data, _ := json.Marshal(&MyStruct{ Value : ?? 10 ?? })
  fmt.Println(string(data))
}
英文:

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

package main

import (
  "fmt"
  "encoding/json"
)

type Nint64 *int64

type MyStruct struct {
   Value Nint64
}

func main() {
  data, _ := json.Marshal(&MyStruct{ Value : ?? 10 ?? })
  fmt.Println(string(data))
}

答案1

得分: 1

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

func NewMyStruct(i int64) *MyStruct {
    return &MyStruct{&i}
}

func main() {
    i := int64(10)
    data, _ := json.Marshal(&MyStruct{Value: Nint64(&i)})
    fmt.Println(string(data))
    //或者这样
    data, _ = json.Marshal(NewMyStruct(20))
    fmt.Println(string(data))
}
英文:

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

func NewMyStruct(i int64) *MyStruct {
	return &amp;MyStruct{&amp;i}
}

func main() {
	i := int64(10)
	data, _ := json.Marshal(&amp;MyStruct{Value: Nint64(&amp;i)})
	fmt.Println(string(data))
    //or this
	data, _ = json.Marshal(NewMyStruct(20))
	fmt.Println(string(data))
}

答案2

得分: 1

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

package main

import (
    "encoding/json"
    "fmt"
)

type Nint64 int64

type MyStruct struct {
    Value Nint64
}

func main() {
    data, _ := json.Marshal(&MyStruct{Value: Nint64(10)})

    fmt.Println(string(data))
}

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

英文:

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

package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
)

type Nint64 int64

type MyStruct struct {
	Value Nint64
}

func main() {
	data, _ := json.Marshal(&amp;MyStruct{Value: Nint64(10)})

	fmt.Println(string(data))
}

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:

确定