Skip to content

Instantly share code, notes, and snippets.

@doorbash
Created October 11, 2022 12:08
Show Gist options
  • Save doorbash/42b36b193ff619c134c080833716aa80 to your computer and use it in GitHub Desktop.
Save doorbash/42b36b193ff619c134c080833716aa80 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"reflect"
)
type Room struct {
name string
roomId int
}
type RoomHandler interface {
PrintRoomName()
PrintRoomId()
}
type MyAwesomeRoomHandler struct {
r *Room
}
func (m *MyAwesomeRoomHandler) PrintRoomId() {
log.Println("MyAwesomeRoomHandler:", m.r.roomId)
}
func (m *MyAwesomeRoomHandler) PrintRoomName() {
log.Println("MyAwesomeRoomHandler:", m.r.name)
}
func NewMyAwesomeHandler(r *Room) *MyAwesomeRoomHandler {
return &MyAwesomeRoomHandler{
r: r,
}
}
var roomHandlers map[string]reflect.Value
func AddRoomHandler[T any](name string, x T) {
roomHandlers[name] = reflect.ValueOf(x)
}
func main() {
roomHandlers = make(map[string]reflect.Value)
AddRoomHandler("awesome", NewMyAwesomeHandler)
x := roomHandlers["awesome"]
r := Room{
name: "room-1",
roomId: 1,
}
y := x.Call([]reflect.Value{reflect.ValueOf(&r)})[0].Interface().(RoomHandler)
y.PrintRoomId()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment