不同命名空间中的golang通用结构

avwztpqn  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(64)

我有160多个.xsd模式,对于每个文件,我都用xsdgen生成xsd.go文件,但每个文档都有CommonType的公共Header。

namespace some_document

type Document struct {
    Header CommonType `xml:"header"`
        // Other fields
}

type CommonType struct {
    A  A `xml:"a"`
    B  B `xml:"b"`
    C1 C `xml:"c1"`
    C2 C `xml:"c2"`
    D  D `xml:"d"`
}

type A string

type B string

type C string

type D string

个字符
另外,我为每个模式创建了一个构建它的函数。我想创建一个函数BuildHeader,并在构建器的函数中重用它。有没有办法用这个类型创建公共命名空间,并使用它来代替any_document.CommonType和some_document.CommonType?我不想编辑代码生成的文件。

namespace common

type CommonType struct {
    A  A `xml:"a"`
    B  B `xml:"b"`
    C1 C `xml:"c1"`
    C2 C `xml:"c2"`
    D  D `xml:"d"`
}

type A string

type B string

type C string

type D string


我的想法:
1.提取包“common”中的Header,并将每个文档的CommonType更改为common.CommonType
1.......

cngwdvgl

cngwdvgl1#

如果你正在处理生成的结构,没有简单的方法来做到这一点。但是,你可以编写一个函数来初始化公共头,并将其用于所有生成的类型,前提是它们在结构上是相同的。

package initializer

type CommonType struct {
  // Identical fields of the common type in all the packages
...
}

func NewCommonType() CommonType {
   // initialize an instance of CommonType
   return commonType
}

字符串
然后您可以使用:用途:

var doc1 pkg1.Document
var doc2 pkg2.Document
...
doc1.CommonType = pkg1.CommonType(initializers.NewCommonType())
doc2.CommonType = pkg2.CommonType(initializers.NewCommonType())

相关问题