亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 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 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號