Golang Cast interface to struct

To answer the question directly, i.e., to cast an interface into a concrete type, you do:

v = i.(T)

where i is the interface and T is the concrete type. It will panic if the underlying type is not T. To have a safe cast, you use:

v, ok = i.(T)

and if the underlying type is not T, ok is set to false, otherwise true. Note that T can also be an interface type and if it is, the code cast i into a new interface instead of a concrete type.

And please be noted, casting an interface is likely a symbol of bad design. As in your code, you should ask yourself, does your custom interface Connection solely requires GetClient or does it always requires a GetValue? Does your GetRedisValue function requires a Connection or does it always wants a concrete struct?

Change your code accordingly.


Your Connection interface:

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

only says that there is a GetClient method, it says nothing about supporting GetValue.

If you want to call GetValue on a Connection like this:

func GetRedisValue(c Connection, key string) (string, error) {
    value, err := c.GetValue(key)
    return value, err
}

then you should include GetValue in the interface:

type Connection interface {
    GetClient() (*redis.Client, error)
    GetValue(string) (string, error) // <-------------------
}

Now you're saying that all Connections will support the GetValue method that you want to use.

Tags:

Go

Redis