• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang Cast 接口(interface)到结构体

[复制链接]
菜鸟教程小白 发表于 2022-8-16 06:38:45 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

嗨,我正在尝试检索一个结构的函数/方法,但我使用一个接口(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
}



Best Answer-推荐答案


直接回答问题,即投 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap