It is possible to pass the value as an interface{}
, then use a type switch to detect which type was passed. Alternatively you can create an interface that exposes the common functionality you need and simply use that.
Interface and type switch:
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)
}
}
Common 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
}
Which method is best for you depends on exactly what you are doing. If most of your types are similar with small differences one or more common interfaces are probably best, if they are quite different then a type switch may be better. Whichever one produces the shortest, clearest code.
Sometimes it is even best to use a mix of the two methods...