Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign struct to interface

Tags:

go

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 ?

like image 526
ceth Avatar asked Mar 20 '26 16:03

ceth


1 Answers

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".

like image 132
VonC Avatar answered Mar 23 '26 11:03

VonC