doudu5498 2018-12-17 22:25
浏览 34
已采纳

如何在Golang中的类型内模拟类型?

The package 'gopkg.in/redis.v3' contains some code

type Client struct {
}

func (*client) Eval (string, []string, []string) *Cmd {
}

type Cmd struct {
}

func (*Cmd) Result () (interface{}, error) {
}

Which works successfully in the following way

func myFunc (cli *redis.Client) {
    result, err := cli.Eval('my script').Result()
}

The problem is that sometimes the Redis cluster gets hammered, has a moment, and the interface returned as a result is nil.

This is reasonably easy to handle but I wish to put a test in place that will ensure that it is actually handled and no type assertion panic occurs.

Traditionally I would insert a mock Redis client into myFunc that can ultimately return nil.

type redisClient interface {
    Eval(string, []string, []string) redisCmd
}

type redisCmd interface {
    Result() (interface{}, error)
}

func myFunc (cli redisClient) {
    result, err := cli.Eval('my script').Result()
}

The problem I am facing is the compiler doesn't recognise that redis.Client satisfies the interface redisClient because it doesn't recognise that the redis.Cmd returned from Eval satisfies redisCmd.

> cannot use client (type *redis.Client) as type redisClient in argument to myFunc:
>    *redis.Client does not implement redisClient (wrong type for Eval method)
>          have Eval(sting, []string, []string) *redis.Cmd
>          want Eval(sting, []string, []string) redisCmd
  • 写回答

1条回答 默认 最新

  • dongshuan8722 2018-12-17 22:34
    关注

    The problem is that your interface does not match the redis client. If you change the interface to:

    type redisClient interface {
        Eval(string, []string, []string) *redis.Cmd
    }
    

    it will compile. That being said, it looks like you really want rediscmd, so you will need to make a wrapper around the redis client:

    type wrapper struct{
      c *redis.Client
    }
    
    func (w wrapper) Eval(x sting, y []string, z []string) redisCmd {
      return w.c.Eval(x,y,z) // This assumes that *redis.Cmd implements rediscmd
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?