Home > Backend Development > Golang > Why Does Golang Throw a 'cannot use function (type func()) as type in argument' Error When Passing Functions?

Why Does Golang Throw a 'cannot use function (type func()) as type in argument' Error When Passing Functions?

Patricia Arquette
Release: 2024-12-11 09:37:10
Original
667 people have browsed it

Why Does Golang Throw a

"cannot use function (type func()) as type in argument"

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
Copy after login

However, the expected type signature for the message handler function is:

type MessageHandler func(MessageDelivery) (interface{}, error)
Copy after login

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)
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template