Go 中的接口和层次结构(从 Java 迁移)

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

我正在用 Go 重写一些旧的 Java 应用程序。该应用程序基于 JAXB 技术构建,并且具有可投影为 XML 的类层次结构。我重写了大部分应用程序,没有任何问题,但对我来说,一个功能似乎没有以正确的方式实现。我给你举个例子。

有一个基本的抽象类 Command,其方法为 toXML 和很多后代(实际上超过 1 层深)

class Command {
    String id;
    String toXML() {
        // every descendant of Command use this method to marshall its structure to XML
    }
}

class SendCommand extends Command {
    String sendData;
}

在 Go 中我实现了下面的代码。

type ToXMLInterface interface {
    ToXML()
}

type Command struct {
    id string
}

func (Command) ToXML() {}

type SendCommand struct {
    Command
    sendData string
}

func (SendCommand) ToXML() {}

func ToXML(value ToXMLInterface) string {
    m, _ := xml.MarshalIndent(value, "", "   ")
    return string(m)
}

但对我来说,它看起来有点奇怪,我想简化它。有什么方法可以做得更简单吗? (也许没有为每个类实现空接口?)

go inheritance interface
1个回答
0
投票

你能详细说明一下你对空接口做什么吗?

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