Here is my code:
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 implements all methods of ICacheEngine. I can pass RedisCache to the method which get ICacheEngine:
func test(something ICacheEngine) *ICacheEngine {
return &something
}
....
appCache.Cache = test(redisCache)
But I cannot assign RedisCache to ICacheEngine. Why ? How can I avoid test() function ? And what will be looking programming with interfaces when I set concrete type to interface and next call it methods ?
Considering an interface can store a stuct or a pointer to a struct, make sure to define your ApplicationCache struct as:
type ApplicationCache struct {
Cache ICacheEngine
}
See "Cast a struct pointer to interface pointer in Golang".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With