In Go, dynamic method dispatch based on the type of an object can be achieved using reflection. Here's an example of how to implement it:
import (
"reflect"
)
type MyInterface interface {
MyMethod()
}
type MyStructA struct{}
func (s MyStructA) MyMethod() {
// Do something specific to MyStructA
}
type MyStructB struct{}
func (s MyStructB) MyMethod() {
// Do something specific to MyStructB
}
func DynamicDispatch(object MyInterface) {
// Get the type of the object
objectType := reflect.TypeOf(object)
// Get the method to call based on the object's type
method := objectType.MethodByName("MyMethod")
// Check if the method exists
if method.IsValid() {
// Call the method on the object
method.Func.Call([]reflect.Value{reflect.ValueOf(object)})
}
}
DynamicDispatch
function:func main() {
objA := MyStructA{}
objB := MyStructB{}
DynamicDispatch(objA) // Calls MyMethod() of MyStructA
DynamicDispatch(objB) // Calls MyMethod() of MyStructB
}
By using reflection, the DynamicDispatch
function can determine the type of the object and call the correct method accordingly.