Hi I'm trying to retrieve the function/method of one struct but I'm using an interface as parameter and using this interface I'm trying to access the function of the struct. To demonstrate what I want below is my code
// Here I'm trying to use "GetValue" a function of RedisConnection but since "c" is an interface it doesn't know that I'm trying to access the RedisConnection function. How Do I fix this?
func GetRedisValue(c Connection, key string) (string, error) {
value, err := c.GetValue(key)
return value, err
}
// Connection ...
type Connection interface {
GetClient() (*redis.Client, error)
}
// RedisConnection ...
type RedisConnection struct {}
// NewRedisConnection ...
func NewRedisConnection() Connection {
return RedisConnection{}
}
// GetClient ...
func (r RedisConnection) GetClient() (*redis.Client, error) {
redisHost := "localhost"
redisPort := "6379"
if os.Getenv("REDIS_HOST") != "" {
redisHost = os.Getenv("REDIS_HOST")
}
if os.Getenv("REDIS_PORT") != "" {
redisPort = os.Getenv("REDIS_PORT")
}
client := redis.NewClient(&redis.Options{
Addr: redisHost + ":" + redisPort,
Password: "", // no password set
DB: 0, // use default DB
})
return client, nil
}
// GetValue ...
func (r RedisConnection) GetValue(key string) (string, error) {
client, e := r.GetClient()
result, err := client.Ping().Result()
return result, nil
}
question from:
https://stackoverflow.com/questions/50939497/golang-cast-interface-to-struct 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…