在Go中调用特定类型的函数
我是个十足的新手,很抱歉提前问了这个问题 我正在尝试使用如此定义的接口连接到message broker:在Go中调用特定类型的函数,go,go-micro,Go,Go Micro,我是个十足的新手,很抱歉提前问了这个问题 我正在尝试使用如此定义的接口连接到message broker: // Broker is an interface used for asynchronous messaging. type Broker interface { Options() Options Address() string Connect() error Disconnect() error Init(...Option) error
// 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)
},
)
错误输出为无法将func literal(type func(broker.Publication))用作natsBroker.Subscribe的参数中的类型broker.Handler
但是如何确保函数类型实际上是一个
broker.Handler
谢谢你的时间提前
更新
如果有人感兴趣,则错误返回类型丢失,这导致了错误,因此它应该类似于:
纳茨布鲁克,订阅(
“队列名称”,
broker.Handler(func(p broker.Publication)错误{
fmt.Printf(p.Topic())
归零
}),
)如果匿名函数的签名与处理程序类型声明的签名相匹配(Adrian正确地指出您缺少错误返回),您应该能够执行以下操作:
由于编译器在编译时知道类型匹配,因此无需进行额外的检查,例如,在发生。错误时,参数和传递的内容不匹配:
type Handler func(Publication) error
func(p broker.Publication)
您没有返回值。如果您添加一个返回值(即使您总是返回
nil
),它也会工作得很好。谢谢Keith,我能够使它工作:)我为任何对具体用例感兴趣的人更新了我的答案“您的匿名函数的签名与处理程序类型声明的签名匹配”不,它不匹配。匿名函数没有返回,该参数接受一个返回error
的函数。哦,你说得对@Adrian,我错过了。我已经更新了答案,谢谢。一个可编辑的答案+1谢谢Adrian,正如你所看到的,我已经更新了我的问题,因为这是关键点:)
type Handler func(Publication) error
func(p broker.Publication)