包'gopkg.in/redis.v3'包含一些代码
type Client struct {
}
func (*client) Eval (string, []string, []string) *Cmd {
}
type Cmd struct {
}
func (*Cmd) Result () (interface{}, error) {
}
Run Code Online (Sandbox Code Playgroud)
以下列方式成功运作
func myFunc (cli *redis.Client) {
result, err := cli.Eval('my script').Result()
}
Run Code Online (Sandbox Code Playgroud)
问题是,有时候Redis集群会受到重创,有一刻,并且返回的接口结果为零.
这相当容易处理,但我希望进行一项测试,以确保实际处理并且不会发生类型断言恐慌.
传统上我会将一个模拟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()
}
Run Code Online (Sandbox Code Playgroud)
我面临的问题是编译器无法识别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
Run Code Online (Sandbox Code Playgroud)
问题是您的界面与redis客户端不匹配.如果将界面更改为:
type redisClient interface {
Eval(string, []string, []string) *redis.Cmd
}
Run Code Online (Sandbox Code Playgroud)
它会编译.话虽这么说,看起来你真的想要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
}
Run Code Online (Sandbox Code Playgroud)