Go 如何动态分配静态类型
我在正确实施这一点上有点困难。如果我使用相互嵌入的下面的结构,并将它们推送到SOAP API,则响应将直接解码到响应结构中 我的问题是,除了ResponseBody结构之外的所有东西都会在其他地方使用,在它的每个实现中重复所有这些结构似乎是错误的 因此,我想:Go 如何动态分配静态类型,go,struct,interface,Go,Struct,Interface,我在正确实施这一点上有点困难。如果我使用相互嵌入的下面的结构,并将它们推送到SOAP API,则响应将直接解码到响应结构中 我的问题是,除了ResponseBody结构之外的所有东西都会在其他地方使用,在它的每个实现中重复所有这些结构似乎是错误的 因此,我想: 尽可能保持我的代码的强类型 在别处使用通用soap结构 在运行时分配/创建适当的对象 我是否使用结构?接口?仿制药?还有别的吗 package soapv1 import ( "encoding/xml" ) //Resp
- 尽可能保持我的代码的强类型
- 在别处使用通用soap结构
- 在运行时分配/创建适当的对象
package soapv1
import (
"encoding/xml"
)
//Response
type Response struct {
XMLName xml.Name `xml:"Envelope"`
SoapBody *SOAPBodyResponse
}
//SOAPBodyResponse
type SOAPBodyResponse struct {
XMLName xml.Name `xml:"Body"`
Resp *ResponseBody
FaultDetails *Fault
}
//Fault
type Fault struct {
XMLName xml.Name `xml:"Fault"`
Faultcode string `xml:"faultcode"`
Faultstring string `xml:"faultstring"`
}
//ResponseBody
type ResponseBody struct {
XMLName xml.Name `xml:"loginResponse"`
LoginReturn string `xml:"loginReturn"`
}
// Some other code between here to prepare and post request
// read and parse the response body
result := new(Response)
err = xml.NewDecoder(res.Body).Decode(result)
在解码之前,将
Resp
字段设置为接口{}
,并将其设置为所需类型的实例。。。。还要注意的是,Go中没有泛型,至少现在还没有,所以您可以忘记这个选项。您需要在接口{}
字段上使用xml:,任何“
标记。