DRY structure tags in Go

I parse XML and no more than at every level of the document, there is a description .

Here is an example of a toy:

 <obj> <description>outer object</description> <subobjA> <description>first kind of subobject</description> <foo>some goop</foo> </subobjA> <subobjB> <description>second kind of subobject</description> <bar>some other goop</bar> </subobjB> </obj> 

This means that each involved structure has an identical description member with the identical tag `xml:"description,omitempty"` .

Here's the valid code: http://play.golang.org/p/1-co6Qcm8d

I would prefer description tags to be DRY. The obvious thing to do is something like:

 type Description string `xml:"description,omitempty"` 

and then use the type description . However, only structural members can have tags. See http://play.golang.org/p/p83UrhrN4u for what I want to write; It does not compile.

You can create a description structure and reinsert it, but an access layer adds an indirectness layer.

Is there another way to do this?

+4
source share
1 answer

Embedding a restructured Description structure (as you said) is a way:

(Playground)

 type describable struct{ Description string `xml:"description"` } type subobjA struct { describable XMLName xml.Name `xml:"subobjA"` } type subobjB struct { describable XMLName xml.Name `xml:"subobjB"` } type obj struct { XMLName xml.Name `xml:"obj"` A subobjA B subobjB } 

The specified layer of indirection does not exist. To specify a specification on this topic:

A field or method f of an anonymous field in structure x is called promoted if xf is the legal selector that designates this field or method f.

Promoted fields act like regular structure fields, except that they cannot be used as field names in compound structure literals.

So you can do this:

 err := xml.Unmarshal([]byte(sampleXml), &sampleObj) fmt.Println(sampleObj.Description) fmt.Println(sampleObj.A.Description) 

sampleObj.describable.Description promoted to sampleObj.Description , so there is no extra layer of indirection.

+4
source

Source: https://habr.com/ru/post/1479422/


All Articles