嗨,我正在尝试检索一个结构的函数/方法,但我使用一个接口(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
}
直接回答问题,即投 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/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |