gpt4 book ai didi

json - Golang 中的继承和 Json

转载 作者:IT王子 更新时间:2023-10-29 01:35:41 28 4
gpt4 key购买 nike

有两个结构体A和B。B包括A。还有一个函数附加到A。它返回父对象的json。当我在 B 的实例上调用函数时,我希望看到 json 中的所有对象字段,但我只得到 A 的字段。请看代码:

type A struct {
Foo string
}

type B struct {
A
Bar string
}

func (object *A) toJson() []byte {
res, _ := json.Marshal(&object)
return res
}


func main() {
b := B{}
fmt.Println(string(b.toJson()))
}

我希望得到 {"Foo":"", "Bar":""} 但结果是 {"Foo":""}。第一种方法是为两个结构定义两个单独的函数。但是有第二种解决方案只有一个功能吗?提前谢谢你。

最佳答案

您的方法 toJson() 来自 A 结构。将其更改为 struct B 然后您将获得预期的结果。

package main

import (
"encoding/json"
"fmt"
)

type A struct {
Foo string `json:"foo"`
}

type B struct {
A
Bar string `json:"bar"`
}

func (object *B) toJson() []byte {
res, _ := json.Marshal(&object)
return res
}

func main() {
c := B{}
fmt.Println(string(c.toJson()))
}

关于json - Golang 中的继承和 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528850/

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