1 回答
TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
我認(rèn)為嵌入結(jié)構(gòu)中的路徑應(yīng)該是絕對的,因?yàn)樗小案浮苯Y(jié)構(gòu)都是“子”的一部分。所以你的
type CommandResult struct {
Code int `xml:"code,attr" json:"code"`
Message string `xml:"msg" json:"msg"`
}
應(yīng)該更像
type CommandResult struct {
Code int `xml:"response>result>code,attr" json:"code"`
Message string `xml:"response>result>msg" json:"msg"`
}
但!我們正面臨著 Go 的局限性。
您不能attr與鏈接一起使用。Github 上有問題,但看起來不在優(yōu)先級列表中。因此,如果我正確理解您的CommandResult聲明的最短版本將是:
type CommandResult struct {
Result struct {
Code int `xml:"code,attr" json:"code"`
Message string `xml:"msg" json:"msg"`
} `xml:"response>result" json:"response"`
}
不是一個(gè)真正的問題,但如果您決定轉(zhuǎn)換Command回 XML 會(huì)很好地聲明它的XMLName. 就像是
type CommandResult struct {
XMLName xml.Name `xml:"epp"`
Result struct {
Code int `xml:"code,attr" json:"code"`
Message string `xml:"msg" json:"msg"`
} `xml:"response>result" json:"response"`
}
因?yàn)闆]有它 XML 編碼器會(huì)產(chǎn)生類似 <SomeCommand><response>...</response></SomeCommand>
使用完整示例更新
package main
import (
"bufio"
"encoding/xml"
"log"
)
type Command interface {
IsError() bool
Request(buf *bufio.Writer, params interface{}) error
}
// Result of request
type CommandResult struct {
XMLName xml.Name `xml:"epp"`
Result struct {
Code int `xml:"code,attr" json:"code"`
Message string `xml:"msg" json:"msg"`
} `xml:"response>result" json:"response"`
}
// this Command's func is realized by CommandResult
func (self CommandResult) IsError() bool {
return true
}
// some command
type SomeCommand struct {
CommandResult
}
// this Command's func is realized by SomeCommand
func (self SomeCommand) Request(buf *bufio.Writer, params interface{}) error {
return nil
}
type AnotherCommand struct {
CommandResult
}
func (self AnotherCommand) Request(buf *bufio.Writer, params interface{}) error {
return nil
}
func main() {
var c Command
c = SomeCommand{}
log.Println(c.IsError())
c = AnotherCommand{}
log.Println(c.IsError())
}
- 1 回答
- 0 關(guān)注
- 197 瀏覽
添加回答
舉報(bào)
