参考内部结构

时间:2018-10-29 04:51:20

标签: go

我正在尝试以编程方式创建一些API文档,我有:

type APIDoc struct {
    Route           string
    ResolutionValue struct {
       v           string
    }
}

然后我尝试这样做:

    json.NewEncoder(w).Encode(APIDoc.ResolutionValue{"foo"})

但它表示

  

APIDoc.ResolutionValue未定义(APIDoc类型没有方法   ResolutionValue)

所以我诉诸于此:

type ResolutionValue struct {
    v string
}

type APIDoc struct {
    Route           string
    ResolutionValue ResolutionValue
}

然后执行:

    json.NewEncoder(w).Encode(ResolutionValue{"foo"})

近亲,有什么方法可以确保完整性吗?

1 个答案:

答案 0 :(得分:1)

从Go 1.11开始,不支持嵌套类型。

Proposal discussion

您的修订版看起来比IMO好很多。

编辑:也许与问题无关,但是您可以使用类型嵌入来简化您的类型。但是,请注意,表示形式有所不同:

type Inner struct {
    Whatever int
}

type ResolutionValue struct {
    Val string
    Inner
}

type ResolutionValue2 struct {
    Val    string
    Inner Inner
}

func main() {

    a, _ := json.Marshal(ResolutionValue{})
    b, _ := json.Marshal(ResolutionValue2{})
    fmt.Printf("%s\n%s", a, b)

}

哪些印刷品:

{"Val":"","Whatever":0}
{"Val":"","Inner":{"Whatever":0}}
相关问题