嗨,我正在尝试检索一个结构的函数/方法,但我使用一个接口(interface)作为参数,并使用该接口(interface)尝试访问该结构的函数。为了演示我想要的下面是我的代码
// 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
}
Best Answer-推荐答案
直接回答问题,即投 interface 进入具体类型,您可以:
v = i.(T)
哪里i 是界面和T 是具体类型。如果底层类型不是 T,它会 panic 。要进行安全转换,您可以使用:
v, ok = i.(T)
如果底层类型不是 T , ok 设置为 false , 否则 true .请注意 T 也可以是接口(interface)类型,如果是,代码转换 i 到一个新的接口(interface)而不是一个具体的类型。
请注意,类型转换一个界面很可能是糟糕设计的象征。正如在您的代码中一样,您应该问问自己,您的自定义界面是否Connection 仅需要 GetClient 还是总是需要 GetValue ?您的 GetRedisValue 函数需要一个 Connection 还是它总是想要一个具体的结构?
相应地更改您的代码。
关于Golang Cast 接口(interface)到结构体,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/50939497/
|