gpt4 book ai didi

go - 如何创建嵌入不同其他对象的可重用对象?

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

我有很多不同的模型:

type objectModel struct {
Title string `json:"title"`
Body string `json:"body"`
}

// Many more models...

这些模型用于创建返回给客户端的响应对象。所有响应必须包含一个 bool 值 OK;其他字段取决于上下文。

type objectResponse struct {
OK bool `json:"ok"`
Object *objectModel `json:"object"`
}

type objectListResponse struct {
OK bool `json:"ok"`
Objects []*objectModel `json:"objects"`
}

// Many more response types that are similar to these two examples.

问题

我想要的是一个可重复使用的 response 对象,它嵌入了所有这些不同的自定义响应对象 objectResponseobjectListResponse 等等。在这种情况下,我不需要在我拥有的每个响应对象上定义 OK bool。我会像这样使用它:response.write(responseWriter),但这超出了这个问题的范围。

type response struct {
OK bool `json:"ok"`
CustomResponse
}

接口(interface)应该可以,但我不知道所有的响应应该实现什么通用方法。

最佳答案

What I want to have is a reusable response object that embeds all these different custom response objects objectResponse, objectListResponse and so on. In this case I wouldn't need to define OK bool on every response object I have.

反其道而行之:有一个可重用的 Response 对象嵌入到您的自定义响应对象中?这将允许您不在每个响应对象(您声明的目标)上定义 OK bool,您只需在每个响应对象中嵌入 Response 结构。如果还有其他重复字段,您也可以对这些字段使用相同的嵌入式结构,或者如果它们仅属于某些自定义响应,则使用另一个结构。

这是一个简化的工作示例:

package main

import(
"fmt"
"encoding/json"
)

type Response struct {
OK bool `json:"ok"`
}

type lookResponse struct {
Response
Color string `json:"color"`
Shape string `json:"shape"`
}

func main() {
b := []byte(`{"ok":true,"color":"blue","shape":"circle"}`)
var r lookResponse
err := json.Unmarshal(b, &r)
if err != nil {
fmt.Printf("Error: %s\n", err)
}
fmt.Printf("ok: %v, color: %v, shape: %v\n", r.OK, r.Color, r.Shape)
}

运行时打印:

ok: true, color: blue, shape: circle

您可以在 Go Language Specification 中阅读有关嵌入式字段的更多信息,例如:

A field declared with a type but no explicit field name is called an embedded field... A field or method f of an embedded field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f. Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

如果这不能解决您的问题,请阐明您的目标/问题。

关于go - 如何创建嵌入不同其他对象的可重用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576048/

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