当前位置: > > > > 在 go 中使用 struct 作为包装器
在 go 中使用 struct 作为包装器
来源:stackoverflow
2024-04-23 08:51:26
0浏览
收藏
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《在 go 中使用 struct 作为包装器》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
如何将 redis.client 包装到我的 struct 中?我有该代码并给了我一个错误
package main
import (
"github.com/go-redis/redis"
)
var cache *rediscache
// rediscache struct
type rediscache struct {
*redis.client
}
func initcache() *rediscache {
if cache == nil {
cache = redis.newclient(&redis.options{
addr: "localhost:6379",
password: "",
db: 0,
})
}
return cache
}
cannot use redis.NewClient(&redis.Options literal) (type *redis.Client) as type *RedisCache in assignment
有一些方法可以转换该属性吗?
解决方案
redis.newclient() 返回 *redis.client 类型的值。使用 创建 rediscache 的值,您可以将其分配给 cache:
func initCache() *RedisCache {
if cache == nil {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
cache = &RedisCache{Client: client}
}
return cache
}
到这里,我们也就讲完了《在 go 中使用 struct 作为包装器》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注米云公众号,带你了解更多关于的知识点!
