Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
继承及;Golang中的Json_Json_Go - Fatal编程技术网

继承及;Golang中的Json

继承及;Golang中的Json,json,go,Json,Go,有两种结构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

有两种结构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:“}。第一种方法是为这两种结构定义两个单独的函数。但是有没有第二个解决方案,只有一个函数?提前感谢。

您的methodn toJson()来自一个结构。将其更改为structb,您将获得预期的结果

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

由于
toJson
是为
A
定义的,因此它在
b.A
上运行。在Go中嵌入类型与在其他语言中进行子类化不同。请参阅。

这是我在问题中描述的第一种方式。在这种情况下,我需要定义两个单独的函数来用于A和B。但是Go中是否存在任何选项来定义一个单独的函数来同时适用于这两种结构,就像经典OOP中的method一样?我不认为您可以在Go中这样做,因为这里的Go没有继承,只有嵌入。你可以在这里看到关于嵌入的文档。就像Andy Answer和这段视频解释了如何编写Go的所有概念。希望能有帮助