登录
首页 >  Golang >  Go问答

在1.18版本中,如何在Unmarshal中应用泛型

来源:stackoverflow

时间:2024-02-08 18:27:24 432浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《在1.18版本中,如何在Unmarshal中应用泛型》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我是 golang 泛型的新手,并进行了以下设置。

  1. 我收集了大量不同类型的报告。
  2. 每个报告都有封闭字段
  3. 所以我将它包装在 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"`
}

unmarshal 时,我使用判别器 reporttype 来确定具体类型。

type reporttype string

const (
    reporttypeexportdatapointreport reporttype = "exportdatapointreport"
    reporttypeimportdatapointreport reporttype = "importdatapointreport"
    reporttypemissingdatapointreport reporttype = "missingdatapointreport"
    reporttypesensorthresoldreport reporttype = "sensorthresoldreport"
)

由于go不支持struct的类型断言(仅接口),因此在unmarshal时无法转换类型。另外,go 不支持指向“raw”泛型类型的指针。因此,我创建了 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
    }

    switch temp.ReportType {
    case ReportTypeExportDataPointReport:
        var report ExportDataPointReport
        err := json.Unmarshal(*temp.Body, &report)
        return &ReportContainerImpl[ExportDataPointReport]{
            LocationID: temp.LocationID,
            Provider:   temp.Provider,
            ReportType: temp.ReportType,
            Body:       report,
        }, err

      // ...
    }
}

正确答案


但是无论我这样做,我总是会在某个地方需要一个接口{}或在 unmarshal 之前知道确切的类型

正是如此。

实例化某些泛型类型或函数(例如 reportcontainerimplunmarshalreportcontainer)所需的具体类型必须在编译时(编写代码时)已知。当您使用实际数据填充字节切片时,json 解组会在运行时发生。

要根据某些歧视性值解组动态 json,您仍然需要 switch

您对如何以类型(更安全)的方式解决此问题有更好的建议吗?

放弃参数多态性。这里不太适合。使用 json.rawmessage 保留现在的代码,在 switch 中有条件地解组动态数据,并返回实现 reportcontainer 接口的具体结构。

作为通用解决方案 - 当且仅当您可以克服这个先有鸡还是先有蛋的问题并在编译时已知类型参数时,您可以编写一个最小的通用解组函数,如下所示:

func unmarshalany[t any](bytes []byte) (*t, error) {
    out := new(t)
    if err := json.unmarshal(bytes, out); err != nil {
        return nil, err
    }
    return out, nil
}

这只是为了说明原理。请注意, json.unmarshal 已经接受任何类型,因此,如果您的泛型函数实际上除了 new(t) 并返回之外什么都不做,就像在我的示例中一样,它与“内联”整个事物没有什么不同,就好像 unmarshalany 不存在一样.

v, err := unmarshalany[sometype](src)

功能等同于

out := &SomeType{}
err := json.Unmarshal(bytes, out)

如果您计划在 unmarshalany 中放入更多逻辑,则可能需要使用它。你的旅费可能会改变;一般来说,当实际上没有必要时不要使用类型参数。

好了,本文到此结束,带大家了解了《在1.18版本中,如何在Unmarshal中应用泛型》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>