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 - 使用私有(private) git 存储库时 go 工作区的结构

python - Go build不会从脾气暴躁的生成Go代码生成二进制文件吗?

go - 加密的确定性伪随机字节

Go接口(interface)方法使用

docker - 如何为微服务应用程序配置 docker 公开端口?

go-micro kubernetes greeter 示例 - 无法访问 greeter api 服务

go - 如何为 Go-Micro 服务修复端口

docker - 通过Traefik从Go客户端调用gRPC服务(Go-micro)

python - HTML到文本,例如Python的BeautifulSoup