2017-10-14 77 views
0

在围棋,如何获得Go中继承结构的属性?

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

我可以统称通过这些,然后以某种方式检查类型?我研究了接口,但是这些看起来是为了继承函数。根据名称,这是一个数据包系统,我怎么能通过任何这些数据包作为参数的函数,检查类型,并得到结构的属性等,如果这是不可能的,那么我将如何在Go中最好实现一个数据包系统?

回答

0

可以将值作为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) 
    } 
} 

通用接口:

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 
} 

哪种方法最适合你取决于你在做什么。如果大多数类型的差别很小,那么一个或多个常用接口可能是最好的,如果它们非常不同,那么类型切换可能会更好。无论哪个产生最短,最清晰的代码。

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