我是 golang 泛型的新手,具有以下设置。
我收集了大量不同类型的报告。
每个报告都有封闭的字段
所以我把它包裹在一个ReportContainerImpl
我使用了一个类型参数, [T Reportable]
其中Reportable
定义如下
type Reportable interface {
ExportDataPointReport | ImportDataPointReport | MissingDataPointReport | SensorThresoldReport
}
类型约束中的每个类型都是要嵌入到容器中的结构。
type ReportContainerImpl[T Reportable] struct {
LocationID string `json:"lid"`
Provider string `json:"pn"`
ReportType ReportType `json:"m"`
Body T `json:"body"`
}
我使用鉴别ReportType器来确定具体类型 when Unmarshal。
type ReportType string
const (
ReportTypeExportDataPointReport ReportType = "ExportDataPointReport"
ReportTypeImportDataPointReport ReportType = "ImportDataPointReport"
ReportTypeMissingDataPointReport ReportType = "MissingDataPointReport"
ReportTypeSensorThresoldReport ReportType = "SensorThresoldReport"
)
由于go不支持struct的类型断言(仅接口),因此无法在Unmarshal. go也不支持指向“原始”泛型类型的指针。因此,我创建了一个实现的接口ReportContainerImpl。
type ReportContainer interface {
GetLocationID() string
GetProvider() string
GetReportType() ReportType
GetBody() interface{}
}
然后我得到的问题是我不能以任何形式或形状对返回类型进行类型约束,并且回到函数的“自由文本语义”以GetBody()允许在完成时进行类型断言Unmarshal。
container, err := UnmarshalReportContainer(data)
if rep, ok := container.GetBody().(ExportDataPointReport); ok {
// Use the ReportContainerImpl[ExportDataPointReport] here...
}
也许我弄错了?- 但无论我这样做,我总是在某个地方结束之前需要一个interface{}或知道确切的类型Unmarshal
你有更好的建议如何以一种类型(更安全)的方式解决这个问题吗?
干杯,马里奥 :)
为了完整起见,我在UnmarshalReportContainer这里添加
func UnmarshalReportContainer(data []byte) (ReportContainer, error) {
type Temp struct {
LocationID string `json:"lid"`
Provider string `json:"pn"`
ReportType ReportType `json:"m"`
Body *json.RawMessage `json:"body"`
}
var temp Temp
err := json.Unmarshal(data, &temp)
if err != nil {
return nil, err
}
凤凰求蛊
相关分类