簡體   English   中英

Golang Cast接口到struct

[英]Golang Cast interface to struct

嗨,我正在嘗試檢索一個結構的函數/方法,但我使用接口作為參數,並使用此接口我試圖訪問結構的功能。 為了證明我想要的是下面的代碼

// 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,它會感到恐慌。要進行安全演員,你可以使用:

v, ok = i.(T)

如果底層類型不是T ,則ok設置為false ,否則為true 請注意, T也可以是接口類型,如果是,則代碼將i轉換為新接口而不是具體類型。

請注意,構建界面可能是糟糕設計的象征。 在您的代碼中,您應該問自己,您的自定義接口Connection僅需要GetClient還是總是需要GetValue 您的GetRedisValue函數是需要Connection還是它總是需要一個具體的結構?

相應地更改您的代碼。

您的Connection界面:

type Connection interface {
    GetClient() (*redis.Client, error)
}

只說有一個GetClient方法,它沒有提到支持GetValue

如果你想在這樣的Connection上調用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)
    GetValue(string) (string, error) // <-------------------
}

現在你說所有的Connection都支持你想要使用的GetValue方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM