doukuo9116 2019-06-18 22:32 采纳率: 100%
浏览 32
已采纳

创建使用指针接收器方法包装现有类型的接口

I need to test an app which uses Google Cloud Pubsub, and so must wrap its types pubsub.Client and pubsub.Subscriber for testing purposes. However, despite several attempts I can't get an interface around them which compiles.

The definitions of the methods I'm trying to wrap are:

func (s *Subscription) Receive(
    ctx context.Context, f func(context.Context, *Message)) error

func (c *Client) Subscription(id string) *Subscription

Here is the current code. The Receiver interface (wrapper around Subscriber) seems to work, but I suspect it may need to change in order to fix SubscriptionMaker, so I've include both.

Note: I've tried several variations of where to reference and dereference pointers, so please don't tell me to change that unless you have an explanation of why your suggested configuration is the correct one or you've personally verified it compiles.

import (
    "context"

    "cloud.google.com/go/pubsub"
)

type Receiver interface {
    Receive(context.Context, func(ctx context.Context, msg *pubsub.Message)) (err error)
}

// Pubsub subscriptions implement Receiver
var _ Receiver = &pubsub.Subscription{}

type SubscriptionMaker interface {
    Subscription(name string) (s Receiver)
}

// Pubsub clients implement SubscriptionMaker
var _ SubscriptionMaker = pubsub.Client{}

Current error message:

common_types.go:21:5: cannot use "cloud.google.com/go/pubsub".Client literal (type "cloud.google.com/go/pubsub".Client) as type SubscriptionMaker in assignment:
    "cloud.google.com/go/pubsub".Client does not implement SubscriptionMaker (wrong type for Subscription method)
        have Subscription(string) *"cloud.google.com/go/pubsub".Subscription
        want Subscription(string) Receiver
  • 写回答

2条回答 默认 最新

  • dongxing2710 2019-06-18 22:56
    关注

    It can't be done.

    When defining the type signature of a method on an interface, it must match exactly. func (c *Client) Subscription(id string) *Subscription returns a *Subscription, and a *Subscription is a valid Receiver, but it does not count as conforming to the interface method Subscription(string) Receiver. Go requires precise matching for function signatures, not the duck-typing style that it usually uses for interfaces.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 WPF动态创建页面内容
  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线