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

标签 go

当它是其中一种数字类型的引用类型别名时,我不知道如何初始化结构字段:

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))
}

最佳答案

你不能,你将不得不添加一个额外的步骤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))
    //or this
    data, _ = json.Marshal(NewMyStruct(20))
    fmt.Println(string(data))
}

关于go - 如何在结构初始化器中使用指针类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644676/

相关文章:

go - 为什么 Go 没有计算整数绝对值的函数?

json - 无法在 gqlgen 中生成标量 JSON

go - Go 中的高级函数

docker - Golang Docker API : get events

go - 如何确保 Kubernetes 中的优雅扩展?

go - golang检查udp端口打开

http - 从网址中删除结尾的斜杠-转到静态服务器

string - 如何在 Go 中分隔数组(类型结构)?

logging - 如何使用golang客户端写入连续写入influxdb

go - 错误: Invalid value "sasl_ssl" for configuration property "security.protocol")