In Go,
type PacketType1 struct {
myValue string
}
type PacketType2 struct {
myValue2 string
}
Can I pass these generically and then check the type somehow? I looked into interfaces, however those seem to be for inheriting functions. Based on the names, this is for a packet system, how could I pass any of these packets to a function as an argument, check the type, and get properties of structs, etc. If this isn't possible, then how would I best implement a packet system in Go?
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...