我有兩個包含不同數據的公共結構,以及一個包含兩個公共結構之一的私有中間結構。我還有一個函數可以解組中間結構,確定它包含哪個公共結構,并返回兩個公共結構之一。我面臨的問題是最后一個函數的返回值。最簡單的是,我認為我可以返回*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 類型)。結構是一個關鍵字,有助于聲明包含字段/屬性的類型。Struct1
Struct2
struct1
struct2
Struct1
Struct2
根據您為其余代碼考慮的用例,可以改為嘗試以下任何一種方法:
正如 mkopriva 建議的那樣,返回一個 interface{} 對象,但是您需要使用類型斷言來實際確保該對象
定義一個 Struct1 和 Struct2 都實現的接口,并返回指向它的指針
制作可與 Struct1 或 Struct2 一起使用的單獨函數。這并不一定像聽起來那么糟糕,因為 Go 允許您以與傳遞類型相同的方式傳遞函數(請參閱包
Less()
中的函數示例sort
)。
- 1 回答
- 0 關注
- 183 瀏覽
添加回答
舉報
0/150
提交
取消