gpt4 book ai didi

json - 如何在 golang 结构中声明可为 null 的 json 字段?

转载 作者:行者123 更新时间:2023-12-01 20:08:47 29 4
gpt4 key购买 nike

我通常喜欢在结构中使用原始数据类型的指针,这样当我对它们进行 json.Marshal 时,nil 字段始终会转换为 "field": null 在 json 字符串中。但这将使创建新的结构实例变得困难,因为我无法使用文字。
例如:

type Book struct {
Price *float32 `json:"price"`
Title *string `json:"title"`
Author *string `json:"author"`
}

func main() {
// I can't do this
book := &Book{
Title: "Book1",
}
}

如您所见,当我使用字符串指针时,我无法轻松初始化结构体,除非为每个指针字段声明一个变量并将它们分配给结构体字段。是否可以同时拥有可为空的 json 字段和无需声明额外变量即可轻松初始化结构的功能?

最佳答案

向您的应用添加辅助函数:

func NewString(s string) *string {
return &s
}

然后你可以使用文字:

// You can do this:
book := &Book{
Title: NewString("Book1"),
}

还有提供这些 NewXXX() 函数的库,因此您不必添加它们(例如 github.com/icza/gox/gox ,披露:我是作者)。

查看相关:How do I do a literal *int64 in Go?

关于json - 如何在 golang 结构中声明可为 null 的 json 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60075782/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com