可以将值作为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
}
哪种方法最适合你取决于你在做什么。如果大多数类型的差别很小,那么一个或多个常用接口可能是最好的,如果它们非常不同,那么类型切换可能会更好。无论哪个产生最短,最清晰的代码。
有时甚至最好使用这两种方法的混合...