'gopkg.in/redis.v3'软件包包含一些代码
type Client struct {
}
func (*client) Eval (string, []string, []string) *Cmd {
}
type Cmd struct {
}
func (*Cmd) Result () (interface{}, error) {
}
以下方式可以成功工作
func myFunc (cli *redis.Client) {
result, err := cli.Eval('my script').Result()
}
问题在于,有时Redis集群会受到重击,有片刻,结果返回的接口为nil。
这相当容易处理,但是我希望对它进行测试,以确保它能被实际处理并且不会发生类型断言恐慌。
传统上,我会将模拟Redis客户端插入到myFunc中,最终可以返回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()
}
我面临的问题是编译器无法识别redis.Client满足接口redisClient,因为它无法识别从Eval返回的redis.Cmd满足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
答案 0 :(得分:5)
问题是您的界面与redis客户端不匹配。如果您将界面更改为:
type redisClient interface {
Eval(string, []string, []string) *redis.Cmd
}
它将编译。话虽这么说,您似乎确实想要rediscmd
,所以您将需要对redis客户端进行包装:
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
}