用于 xml 生成的 Golang 泛型

问题描述 投票:0回答:1

我必须生成一个

XML
,我当前的代码如下:


type ReportableSeller struct {
    Identity Identity `xml:"Identity"`
}

type Identity struct {
    EntitySeller     *EntitySeller     `xml:"EntitySeller,omitempty"`
    IndividualSeller *IndividualSeller `xml:"IndividualSeller,omitempty"`
}

type EntitySeller struct {
    Standard StandardEntSeller `xml:"Standard"`
}

type IndividualSeller struct {
    Standard StandardIndSeller `xml:"Standard"`
}

type StandardEntSeller struct {
    EntSellerID EntSellerID `xml:"EntSellerID"`
}

type StandardIndSeller struct {
    IndSellerID IndSellerID `xml:"IndSellerID"`
}

type EntSellerID struct {
}

type IndSellerID struct {
}

使用这些类型,我只需添加一个基于

EntitySeller
IndividualSeller
是否已定义,并且生成正确的
vat
omitempty
但我不太喜欢它,因为我必须定义 

xml

两次,并在 Identity 中使用这两个可为空的变量,而不是强制变量。这个想法是使用泛型。

以下是迄今为止的结构:

Standard

这里的问题是 ReportableSeller 中的 Identity 类型需要通用类型:
type ReportableSeller struct { Identity Identity[here I need a sort of interface] `xml:"Identity"` } type Identity[T any] struct { Seller T } type EntitySeller struct { XMLName xml.Name `xml:"EntitySeller"` Standard Standard[EntSellerID] } type IndividualSeller struct { XMLName xml.Name `xml:"IndividualSeller"` Standard Standard[IndSellerID] } type Standard[T any] struct { XMLName xml.Name `xml:"Standard"` SellerID T } type EntSellerID struct { XMLName xml.Name `xml:"EntSellerID"` } type IndSellerID struct { XMLName xml.Name `xml:"IndSellerID"` }

可以修复吗?

在 C# 中我会使用继承和多态性...

编辑:

与此同时,我得到了以下结果:

cannot use generic type Identity[T any] without instantiation

有了它,我就可以做我需要做的事情,但是,不用打字,也不会出错。

go generics polymorphism
1个回答
0
投票
type Identity struct { Seller any }

就像

ReportableSeller

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.