为了账号安全,请及时绑定邮箱和手机立即绑定

从 Go 中的函数返回指向结构的指针

从 Go 中的函数返回指向结构的指针

Go
小怪兽爱吃肉 2022-12-13 10:59:58
我有两个包含不同数据的公共结构,以及一个包含两个公共结构之一的私有中间结构。我还有一个函数可以解组中间结构,确定它包含哪个公共结构,并返回两个公共结构之一。我面临的问题是最后一个函数的返回值。最简单的是,我认为我可以返回*struct{},但我的 IDE 中一直出现类型不匹配的情况。我很抱歉发布了比可能需要的更多的代码,但我正在努力让它尽可能接近我正在处理的代码。package mainimport (    "encoding/json"    "errors")// These vars are some errors I'll use in the functions later onvar (    errInvaldBase64     = errors.New("invalid base64")    errInvalidStructType = errors.New("invalid struct type"))// Struct1 public structtype Struct1 struct {    FName string `json:"first-name"`    LName string `json:"last-name"`}// Struct2 public structtype Struct2 struct {    Date  string `json:"date"`    Items []int  `json:"items"`}// intermediateStruct private struct// The Type field indicates which kind of struct Data contains (Struct1 or Struct2)// The Data field contains either Struct1 or Struct2 which was previously marshalled into JSONtype intermediateStruct struct {    Type structType    Data []byte}// The following type and const are my understanding of an enum in Go// structType is a private type for the type of struct intermediateStruct containstype structType int// These public constants are just to keep my hands out of providing values for the different struct typesconst (    StructType1 structType = iota    StructType2)// unmarshalStruct1 unmarshalls JSON []byte into a new Struct1 and returns a pointer to that structfunc unmarshalStruct1(b []bytes) (*Struct1, error) {    newStruct1 := new(Struct1)    err := json.Unmarshal(b, newStruct1)    if err != nil {        return nil, errInvalidBase64    }    return newStruct1, nil}// unmarshalStruct2 unmarshalls JSON []byte into a new Struct2 and returns a pointer to that structfunc unmarshalStruct2(b []bytes) (*Struct2, error) {    newStruct2 := new(Struct2)    err := json.Unmarshal(b, newStruct2)    if err != nil {        return nil, errInvalidBase64    }    return newStruct2, nil}我知道有一种方法可以实现我想要实现的目标——我只是缺乏实现目标的经验/理解。感谢您的任何和所有输入!
查看完整描述

1 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

您的函数返回一个指向类型or 的unmarshallStruct指针(取决于调用的函数版本)。因此变量和分别是指向类型和的指针。也不是指向类型 struct 的指针(无论如何我必须添加它不是真正的 Go 类型)。结构是一个关键字,有助于声明包含字段/属性的类型。Struct1Struct2struct1struct2Struct1Struct2

根据您为其余代码考虑的用例,可以改为尝试以下任何一种方法:

  1. 正如 mkopriva 建议的那样,返回一个 interface{} 对象,但是您需要使用类型断言来实际确保该对象

  2. 定义一个 Struct1 和 Struct2 都实现的接口,并返回指向它的指针

  3. 制作可与 Struct1 或 Struct2 一起使用的单独函数。这并不一定像听起来那么糟糕,因为 Go 允许您以与传递类型相同的方式传递函数(请参阅包Less()中的函数示例sort)。


查看完整回答
反对 回复 2022-12-13
  • 1 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信