I'm a Go newcomer and I've been battling with this problem almost all day today.
Considering I have these:
type HandlerType func()
var object interface{}
var typedObject HandlerType
I can assign a function to the typedObject variable like this:
typedHandler = func() {
fmt.Println("in a handler!\n")
}
But what I need to do is to pass that handler function as an interface{} variable and then convert it somehow to HandlerType which I could call later
I've tried this but it throws an error:
typedHandler = object.(HandlerType)
results in:
interface conversion: interface is func(), not main.HandlerType
Basically I need to register functions with different signatures without additional type conversion before registering. So instead of doing this:
registerHandler(HandlerTypeString(func() string { ... }))
registerHandler(HandlerTypeVoid(func() { ... }))
I want to register handlers like this:
registerHandler(func() string { ... })
registerHandler(func() { ... })
.. and I don't want to involve reflection at the time of a handler call later
Is it possible?
Edit: I've created a playground: http://play.golang.org/p/UlwqkHjt_P
So as I understand there is no way to pass some arbitrary function as interface{} and then somehow convert it to HandlerType or some other predefined function type so I would be able to call it without using reflection?
Edit2: I've came up with this solution: http://play.golang.org/p/4gUxsgmiPf
There shouldn't be any performance penalties during runtime with this code. But can somebody think out another way of implementing this functionality without interface{} ?
typedHandler = object.(HandlerType)
will work if object (of typeinterface {}
) really contains an object ofHandlerType
. Show code which is playable on the playground. – Volkerinterface{}
. Finde some other way, writer proper Go code. A newcomer's which forinterface{}
magic smells like code transliteration from some other language. – Volker