gpt4 book ai didi

Golang Cast接口(interface)结构

转载 作者:IT王子 更新时间:2023-10-29 00:33:34 25 4
gpt4 key购买 nike

您好,我正在尝试检索一个结构的函数/方法,但我正在使用一个接口(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 是接口(interface),T 是具体类型。如果底层类型不是 T,它会 panic。要进行安全转换,您可以使用:

v, ok = i.(T)

如果基础类型不是T,ok 设置为false,否则true。请注意,T 也可以是接口(interface)类型,如果是,代码会将 i 转换为新接口(interface)而不是具体类型。

请注意,转换界面很可能是糟糕设计的象征。在您的代码中,您应该问问自己,您的自定义接口(interface) Connection 只需要 GetClient 还是始终需要 GetValue?您的 GetRedisValue 函数需要一个 Connection 还是它总是需要一个具体的结构?

相应地更改您的代码。

关于Golang Cast接口(interface)结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50939497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com