gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:24:08 24 4
gpt4 key购买 nike

在围棋中,

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com