Golang Cast结构接口

Golang Cast结构接口,go,redis,Go,Redis,嗨,我试图检索一个结构的函数/方法,但我使用一个接口作为参数,并使用这个接口,我试图访问该结构的函数。下面是我的代码来演示我想要的 // 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 th

嗨,我试图检索一个结构的函数/方法,但我使用一个接口作为参数,并使用这个接口,我试图访问该结构的函数。下面是我的代码来演示我想要的

// 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
}

您的
连接
界面:

type Connection interface {
    GetClient() (*redis.Client, error)
}
type Connection interface {
    GetClient() (*redis.Client, error)
    GetValue(string) (string, error) // <-------------------
}
只说有一个
GetClient
方法,它没有说明支持
GetValue

如果要在
连接上调用
GetValue
,如下所示:

func GetRedisValue(c Connection, key string) (string, error) {
    value, err := c.GetValue(key)
    return value, err
}
然后您应该在界面中包括
GetValue

type Connection interface {
    GetClient() (*redis.Client, error)
}
type Connection interface {
    GetClient() (*redis.Client, error)
    GetValue(string) (string, error) // <-------------------
}
类型连接接口{
GetClient()(*redis.Client,错误)

GetValue(string)(string,error)//要直接回答问题,即将
接口转换为具体类型,您需要:

v = i.(T)
其中,
i
是接口,
T
是具体类型。如果基础类型不是T,它将死机。要进行安全转换,请使用:

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

请注意,铸造接口很可能是糟糕设计的象征。在您的代码中,您应该问问自己,您的自定义接口
连接
是否只需要
GetClient
,还是总是需要
GetValue
?您的
GetRedisValue
函数是否需要
连接它总是想要一个混凝土结构


相应地更改您的代码。

是的,我想会是这样。但是连接接口将有一个GetValue方法是没有意义的。所以我正在考虑使用一个单独的接口,其中包含一个GetValue函数。我该怎么做呢?这取决于您想走多远。您真的需要
Connection
interface?也许您只需要某种类型的
type Valuer接口{GetValue(string)(string,error)}
然后将您的redis连接包装在实现该接口的结构中。GetValue返回一个接口。使用redis.string()将其转换为string