1 回答

TA貢獻1829條經驗 獲得超7個贊
redis.Client是一種結構類型,并且在 Go 中結構類型根本不可模擬。然而 Go 中的接口是可模擬的,所以你可以做的是定義你自己的“newredisclient”函數,而不是返回一個結構,而是返回一個接口。由于 Go 中的接口是隱式滿足的,因此您可以定義接口,以便它可以由 redis.Client 開箱即用地實現。
type RedisClient interface {
Ping() redis.StatusCmd
// include any other methods that you need to use from redis
}
func NewRedisCliennt(options *redis.Options) RedisClient {
return redis.NewClient(options)
}
var newRedisClient = NewRedisClient
如果您還想模擬 的返回值Ping(),則需要做更多的工作。
// First define an interface that will replace the concrete redis.StatusCmd.
type RedisStatusCmd interface {
Result() (string, error)
// include any other methods that you need to use from redis.StatusCmd
}
// Have the client interface return the new RedisStatusCmd interface
// instead of the concrete redis.StatusCmd type.
type RedisClient interface {
Ping() RedisStatusCmd
// include any other methods that you need to use from redis.Client
}
現在*redis.Client不再滿足接口RedisClient,因為 的返回類型Ping()不同。redis.Client.Ping()請注意, 的結果類型是否滿足 的返回接口類型并不重要RedisClient.Ping(),重要的是方法簽名不同,因此它們的類型不同。
要解決此問題,您可以定義一個*redis.Client直接使用并滿足新RedisClient接口的瘦包裝器。
type redisclient struct {
rc *redis.Client
}
func (c *redisclient) Ping() RedisStatusCmd {
return c.rc.Ping()
}
func NewRedisCliennt(options *redis.Options) RedisClient {
// here wrap the *redis.Client into *redisclient
return &redisclient{redis.NewClient(options)}
}
var newRedisClient = NewRedisClient
- 1 回答
- 0 關注
- 113 瀏覽
添加回答
舉報