go - Go中调用特定类型的函数

标签 go go-micro

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

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

// 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
}

我正在尝试使用订阅功能来订阅 channel ,这就是我现在正在努力的地方。 我目前的方法如下:

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

错误输出为无法在 natsBroker.Subscribe 的参数中使用 func 文字(类型 func(broker.Publication))作为 Broker.Handler 类型
但如何确保函数类型实际上是 Broker.Handler ?

感谢您提前抽出时间!

更新

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

natsBroker.订阅( “队列名称”, Broker.Handler(func(p Broker.Publication) 错误 { fmt.Printf(p.Topic()) 返回零 }), )

最佳答案

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

type Handler func(Publication) error

             func(p broker.Publication)

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

关于go - Go中调用特定类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53307233/

相关文章:

go - 如何在 Visual Studio Code VS 上同时修改多个 go/golang 项目?

go - gCloud 实例 : ssh: handshake failed: ssh: unable to authenticate, 尝试的方法 [无公钥],没有支持的方法

go - 无法找出 udemy 类(class)中缺少的 protoc 命令

go - micro_out : protoc-gen-micro: Plugin failed

go - 检查接口(interface)的相等性{}

go - Go中定义的io库在哪里?

go - 如何从源代码手动安装 Go 包

go - 使用 Go Micro 从一个经纪人消费并生产到另一个经纪人

reflection - Go 中的泛型编程。避免硬编码类型断言