我是一个完全的 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/