我來自 Python 背景,這是我第一次正式涉足 Go,所以我認為事情還沒有開始。我目前正在 Go 中實現 Affiliate Window XML API。API 遵循請求和響應的標準結構,因此為此我試圖保持干燥。信封始終具有相同的結構,如下所示:<Envelope> <Header></Header> <Body></Body></Envelope>內容Header和Body依據是什么,我請求,將是不同的反應,所以我創建了一個基地Envelope structtype Envelope struct { XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` NS1 string `xml:"xmlns:ns1,attr"` XSD string `xml:"xmlns:xsd,attr"` Header interface{} `xml:"http://schemas.xmlsoap.org/soap/envelope/ Header"` Body interface{} `xml:"Body"`}這適用于為請求編組 XML,但我在解組時遇到問題:func NewResponseEnvelope(body interface{}) *Envelope { envelope := NewEnvelope() envelope.Header = &ResponseHeader{} envelope.Body = body return envelope}func main() { responseBody := &GetMerchantListResponseBody{} responseEnvelope := NewResponseEnvelope(responseBody) b := bytes.NewBufferString(response) xml.NewDecoder(b).Decode(responseEnvelope) fmt.Println(responseEnvelope.Header.Quota) // Why can't I access this?}這個http://play.golang.org/p/v-MkfEyFPM在代碼中可能比我用文字更好地描述了這個問題:p
1 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
該類型的Header內場Envelope結構是interface{}它是不是一個struct,所以你不能引用任何字段。
為了引用名為 的字段Quota,您必須Header使用包含Quota字段的靜態類型進行聲明,如下所示:
type HeaderStruct struct {
Quota string
}
type Envelope struct {
// other fields omitted
Header HeaderStruct
}
如果您不知道它將是什么類型或者您不能提交單一類型,您可以將其保留為interface{},但是您必須使用類型開關或類型斷言在運行時將其轉換為靜態類型,后者看起來像這樣:
headerStruct, ok := responseEnvelope.Header.(HeaderStruct)
// if ok is true, headerStruct is of type HeaderStruct
// else responseEnvelope.Header is not of type HeaderStruct
另一種選擇是使用反射來訪問Envelope.Header值的命名字段,但如果可能,請嘗試以其他方式解決它。如果您有興趣了解有關 Go 反射的更多信息,我建議您先閱讀The Laws of Reflection博客文章。
- 1 回答
- 0 關注
- 210 瀏覽
添加回答
舉報
0/150
提交
取消