Home >Backend Development >Golang >Why Does My Go Code Produce 'cannot use function as type in argument' and How Can I Fix It?

Why Does My Go Code Produce 'cannot use function as type in argument' and How Can I Fix It?

DDD
DDDOriginal
2024-12-14 07:48:13358browse

Why Does My Go Code Produce

Error "cannot use function as type in argument"

In the provided Go code, you are attempting to pass a function as an argument to another function, but you are encountering the error "cannot use function (type func()) as type in argument." This error indicates that the type of the function you are trying to pass does not match the expected type of the argument.

To resolve this issue, ensure that the signature of the function you are passing matches the expected type of the argument. In your case, you are passing functions that take a MessageDelivery struct as an argument and return a value and error. However, the expected type of the argument expects a function that takes a MessageDelivery struct as an argument and returns an interface{} directly.

To rectify this, modify your functions as follows:

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 modifying your functions to return an interface{} directly, they will now match the expected type of the argument, and the error should be resolved.

The above is the detailed content of Why Does My Go Code Produce 'cannot use function as type in argument' and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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