dtuct88226 2016-03-01 20:38
浏览 282

如何在Golang回调中使用接口?

I am trying to use a Faye client for Go but when I try to make an interface for the client it seems to fail due to to the type in the callback:

package main

import (
    "fmt"
    "github.com/autogrowsystems/wray"
)

type Message interface {
    Data() map[string]interface{}
}

type Promise interface {
    Successful() bool
}

type Subscriber interface {
    Subscribe(string, bool, func(Message)) (Promise, error)
}

func subscribeMe(subber Subscriber) {
    subber.Subscribe("/my/chan", false, func(msg Message) {
        fmt.Printf("got data: %+v", msg.Data())
    })
}

func main() {
    subscribeMe(wray.NewFayeClient("http://localhost/faye"))
    fmt.Println("all good!")
}

At that point it fails with the following error:

# command-line-arguments
main/fayetest.go:27: cannot use wray.NewFayeClient("http://localhost/faye") (type *wray.FayeClient) as type Subscriber in argument to subscribeMe:
    *wray.FayeClient does not implement Subscriber (wrong type for Subscribe method)
            have Subscribe(string, bool, func(wray.Message)) (wray.SubscriptionPromise, error)
            want Subscribe(string, bool, func(Message)) (Promise, error)

It seems as though it should work as the client does satisfy the interface:

// wray.go - wray.FayeClient
func (self *FayeClient) Subscribe(channel string, force bool, callback func(Message)) (promise SubscriptionPromise, err error) {
}

// response.go - wray.Message 
func (self Message) Data() map[string]interface{} {
}

// wray.go - wray.SubscriptionPromise
func (self SubscriptionPromise) Successful() bool {
}

It should work right? Or does the callback mess up the satisfaction of the interface?

Edit: as an aside, I am the author of that fork of the Faye Client, is there anything I can do to make it conducive to interfaces? Apart from ditching callbacks?

  • 写回答

2条回答 默认 最新

  • douxuanjie2692 2016-03-01 21:05
    关注

    FayeClient.Subscribe implements:

    Subscribe(string, bool, func(wray.Message)) (wray.SubscriptionPromise, error)
    

    and your interface Subscriber requires the function:

    Subscribe(string, bool, func(Message)) (Promise, error)
    

    Notice the different parameters of the callback function (Message != wray.Message, Promise != wray.SubscriptionPromise), and that's why your code won't compile.

    You don't need to declare the interfaces Message and Promise again, just use the ones from the library.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度