gpt4 book ai didi

json - 具有非简单类型的 GoLang JSON Marshal omitempty - 可以避免指针吗?

转载 作者:数据小太阳 更新时间:2023-10-29 03:13:24 24 4
gpt4 key购买 nike

下面的代码是解释。我可以使用非简单类型的唯一方法是使该类型成为指针。

是否有不使用指针的替代解决方案?

代码不工作:

type Foo struct {
Bar Bar `json:"bar,omitempty"`
}

type Bar struct {
Baz string `json:"baz"`
}

func main() {

foo := Foo{}

jsonBytes, _ := json.Marshal(foo)

fmt.Printf("%s\n", jsonBytes)
}

输出:{"bar":{"baz":""}}

代码工作,但不是我想要的:

type Foo struct {
Bar *Bar `json:"bar,omitempty"`
}

type Bar struct {
Baz string `json:"baz"`
}

func main() {

foo := Foo{}

jsonBytes, _ := json.Marshal(foo)

fmt.Printf("%s\n", jsonBytes)
}

输出:{}

最佳答案

Is there an alternative solution to this by not using pointers?

没有。

关于json - 具有非简单类型的 GoLang JSON Marshal omitempty - 可以避免指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44693552/

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