【问题标题】:Call function of specific type in GoGo中特定类型的调用函数
【发布时间】:2019-04-17 20:01:36
【问题描述】:

我是一个完整的围棋新手,很抱歉提前提出问题。

我正在尝试使用这样定义的接口来连接到消息代理:

// 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-function 订阅频道,这就是我现在苦苦挣扎的地方。 我目前的方法是以下一种:

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

提前感谢您的时间!

更新

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

natsBroker.Subscribe( "队列名", broker.Handler(func(p broker.Publication)错误{ fmt.Printf(p.Topic()) 返回零 }), )

【问题讨论】:

    标签: go go-micro


    【解决方案1】:

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

    type Handler func(Publication) error
    
                 func(p broker.Publication)
    

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

    【讨论】:

    • 谢谢阿德里安,你可以看到我已经更新了我的问题,因为这是关键点:)
    【解决方案2】:

    如果您的匿名函数的签名与处理程序类型声明的签名匹配(Adrian 正确指出您缺少错误返回),您应该可以只执行 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 的情况下那样进行额外检查。

    【讨论】:

    • 感谢基思,我能够让它工作 :) 我为任何对具体用例感兴趣的人更新了我的答案
    • "您的匿名函数的签名与处理程序类型声明的签名匹配" 不,它没有。匿名函数无返回,参数取一个返回error的函数。
    • 哦,你是对的@Adrian,我错过了。我已经更新了答案,谢谢。
    • 一个可编译的答案 +1
    猜你喜欢
    • 2018-02-19
    • 2013-06-15
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多