登录
首页 >  Golang >  Go问答

Go中调用特定类型的函数

来源:stackoverflow

时间:2024-04-08 15:30:34 433浏览 收藏

大家好,我们又见面了啊~本文《Go中调用特定类型的函数》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我是一个完全的 go 新手,很抱歉提前提出这个问题。

我正在尝试使用如此定义的接口来连接到消息代理:

// broker is an interface used for asynchronous messaging.
type broker interface {
    options() options
    address() string
    connect() error
    disconnect() error
    init(...option) error
    publish(string, *message, ...publishoption) error
    subscribe(string, handler, ...subscribeoption) (subscriber, error)
    string() string
}

// handler is used to process messages via a subscription of a topic.
// the handler is passed a publication interface which contains the
// message and optional ack method to acknowledge receipt of the message.
type handler func(publication) error

// publication is given to a subscription handler for processing
type publication interface {
    topic() string
    message() *message
    ack() error
}

我正在尝试使用 subscribe 函数来订阅频道,这就是我现在正在努力的地方。 我目前的方法如下:

natsBroker.Subscribe(
        "QueueName",
        func(p broker.Publication) {
            fmt.Printf(p.Message)
        },
    )

错误输出为 cannot use func literal (type func(broker.publication)) as typebroker.handler in argument to natsbroker.subscribe

但如何确保函数类型实际上是 broker.handler

感谢您提前抽出时间!

更新

如果有人感兴趣,错误返回类型丢失导致了错误,所以它看起来应该类似于:

natsbroker.订阅( “队列名称”, broker.handler(func(p broker.publication) 错误 { fmt.printf(p.topic()) 返回零 }), )


解决方案


如错误所示,参数和您传递的内容不匹配:

type handler func(publication) error

             func(p broker.publication)

你没有返回值。如果您添加一个返回值(即使您总是返回 nil),它将正常工作。

如果您的匿名函数的签名与处理程序类型声明的签名相匹配(adrian 正确地指出您缺少错误返回),您应该可以执行 type conversion

package main

import "fmt"

type Handler func(int) error

var a Handler

func main() {
    a = Handler(func(i int) error {
        return nil
    })

    fmt.Println(isHandler(a))
}

func isHandler(h Handler) bool {
    return true
}

由于编译器在编译时就知道类型匹配,因此无需进行额外的检查,例如 a type assertion 的情况。

今天关于《Go中调用特定类型的函数》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>