In Golang, when passing a function as an argument to another function, the type signature of the passed function must match the expected signature of the receiving function. In your code, you are attempting to pass the following functions as arguments:
UpperCaseHandler RepeatHandler
However, the expected type signature for the message handler function is:
type MessageHandler func(MessageDelivery) (interface{}, error)
As you can see, the expected message handler function takes a MessageDelivery struct as an argument and returns an interface{} and an error. Your functions, however, are defined as follows:
func UpperCaseHandler(md asl.MessageDelivery) { s.Reply(MessageTest{strings.ToUpper(md.Message.(string))}, md.Delivery) } func RepeatHandler(md asl.MessageDelivery) { s.Reply(MessageTest{strings.Repeat(md.Message.(string), 5)}, md.Delivery) }
Note that your functions are missing the return values (interface{} and error). To fix this, you need to modify your functions to match the expected signature. Here's how you can do it:
func UpperCaseHandler(md asl.MessageDelivery) (interface{}, error} { s.Reply(MessageTest{strings.ToUpper(md.Message.(string))}, md.Delivery) return nil, nil } func RepeatHandler(md asl.MessageDelivery) (interface{}, error} { s.Reply(MessageTest{strings.Repeat(md.Message.(string), 5)}, md.Delivery) return nil, nil }
By adding the missing return values, your functions will now match the expected signature, and you will be able to pass them as arguments to the other functions without encountering the "cannot use function (type func()) as type in argument" error.
The above is the detailed content of Why Does Golang Throw a 'cannot use function (type func()) as type in argument' Error When Passing Functions?. For more information, please follow other related articles on the PHP Chinese website!