作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
这是我的代码:
type ICacheEngine interface {
// ...
}
// implements all methods of ICacheEngine
type RedisCache struct { }
type ApplicationCache struct {
Cache *ICacheEngine
}
func NewRedisCache() *ApplicationCache {
appCache := new(ApplicationCache)
redisCache := new(RedisCache)
appCache.Cache = redisCache // here is an error : can not use *RedisCache as *ICacheEngine
return appCache
}
RedisCache
实现了ICacheEngine
的所有方法。我可以将 RedisCache
传递给获取 ICacheEngine
的方法:
func test(something ICacheEngine) *ICacheEngine {
return &something
}
....
appCache.Cache = test(redisCache)
但是我无法将 RedisCache
分配给 ICacheEngine
。为什么 ?我怎样才能避免 test()
功能?当我将具体类型设置为接口(interface)并接下来调用它方法时,使用接口(interface)进行编程会是什么样子?
最佳答案
考虑到接口(interface)可以存储结构或指向结构的指针,请确保将您的 ApplicationCache 结构定义为:
type ApplicationCache struct {
Cache ICacheEngine
}
关于go - 如何将结构分配给接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51074581/
我是一名优秀的程序员,十分优秀!