简体   繁体   中英

Go - how to define struct field's data type as another struct

How do you define struct's field type as struct?

I want to be able to have something like below:

type HelloResp struct {
  Response struct `xml:resp`
}

func (hr *HelloResp) SetHelloResp(interf interface{}) {
  hr.Response = interf
}

Basically I have a few of other children structs I want to embed as needed under HelloResp.Response so they are interchangeable by functions.

Is this anyway possible or are there any recommended Go way of doing this?

If you use the innerxml field tag you can delay processing until you know what is inside your struct. To do so you would likely need an HTTP header or a field that gives the type. You then unmarshal the response contents based on that type.

type HelloResp struct {
    ResponseType string `xml:responseType`
    Response []byte `xml:response,innerxml`
}

If the struct has a field of type []byte or string with tag ",innerxml", Unmarshal accumulates the raw XML nested inside the element in that field. The rest of the rules still apply.

Another (less desireable) option would be to list all of the possible contained types as pointers. The unmarshaller will populate the one(s) it finds. You would need to figure out which one was set though so a response type is going to be needed either way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM