networking - 如何在 Go 中获取继承结构的属性?

标签 networking go

在围棋中,

type PacketType1 struct {
    myValue string
}
type PacketType2 struct {
    myValue2 string
}

我可以一般地传递​​这些然后以某种方式检查类型吗?我查看了接口(interface),但是这些接口(interface)似乎是用于继承函数的。根据名称,这是针对数据包系统的,我如何将这些数据包中的任何一个作为参数传递给函数,检查类型并获取结构的属性等。如果这不可能,那么我将如何最好在 Go 中实现数据包系统?

最佳答案

可以将值作为接口(interface){}传递,然后使用类型开关检测传递的是哪种类型。或者,您可以创建一个接口(interface)来公开您需要的常用功能,然后简单地使用它。

接口(interface)和类型切换:

func Example(v interface{}){
    switch v2 := v.(type) {
    case PacketType1:
        // Do stuff with v1 (which has type PacketType1 here)
    case PacketType2:
        // Do stuff with v1 (which has type PacketType2 here)
    }
}

通用接口(interface):

type Packet interface{
    GetExample() string
    // More methods as needed
}

// Not shown: Implementations of GetValue() for all types used
// with the following function

func Example(v Packet) {
    // Call interface methods
}

哪种方法最适合您取决于您​​在做什么。如果您的大多数类型都相似,但差异很小,一个或多个通用接口(interface)可能是最好的,如果它们完全不同,那么类型转换可能会更好。以生成最短、最清晰的代码为准。

有时最好混合使用这两种方法...

关于networking - 如何在 Go 中获取继承结构的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46747779/

相关文章:

go - 如何使用Jenkins运行SonarQube for Go代码

docker - Go 1.14 模块构建命令忽略 Docker 中的 vendor 目录

json - go json 结构中的控件显示

java 。从包中获取 URL

创建新的 tcp 套接字 - 服务器端

c++ - 在同一台机器上运行客户端和服务器

android - 如何同步两部或多部安卓手机的系统时钟?

c# - 向 UDP 数据包添加额外的校验和是否值得额外的开销?

http - golang - 似乎无法断开 http 连接

go - 从http请求解码嵌套的json对象返回nil