gpt4 book ai didi

go - 引用内部结构

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

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

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

然后我尝试这样做:

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

但是上面写着

APIDoc.ResolutionValue undefined (type APIDoc has no method ResolutionValue)

所以我采取了这种做法:

type ResolutionValue struct {
v string
}

type APIDoc struct {
Route string
ResolutionValue ResolutionValue
}

然后做:

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

有点蹩脚,有没有办法以某种方式确保完整性?

最佳答案

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

Proposal discussion

在我看来,您的修订版看起来好多了。

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

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

关于go - 引用内部结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53038922/

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