Go中特定类型的调用函数

Call function of specific type in Go

我是一个完整的 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 type broker.Handler in argument to natsBroker.Subscribe
但是如何确保函数类型实际上是 broker.Handler

感谢您提前抽空!

更新

万一有人感兴趣,错误 return 类型丢失导致了错误,所以它看起来应该类似于:

natsBroker.Subscribe( "QueueName", broker.Handler(func(p broker.Publication) 错误 { fmt.Printf(p.Topic()) return 无 }), )

如果您的匿名函数签名与处理程序类型声明的签名相匹配(Adrian 正确地指出您遗漏了错误 return),您应该可以只执行 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.

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

type Handler func(Publication) error

             func(p broker.Publication)

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