代码之家  ›  专栏  ›  技术社区  ›  ceth

如何将结构分配给接口

go
  •  0
  • ceth  · 技术社区  · 7 年前

    这是我的代码:

    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 .我可以通过 再缓存 到一种方法 淫羊藿 以下内容:

    func test(something ICacheEngine) *ICacheEngine {
        return &something
    }
    
    ....
    
    appCache.Cache = test(redisCache)
    

    但我不能指派 再缓存 淫羊藿 是的。为什么?我怎样才能避免 test() 功能?当我将具体类型设置为interface并下一次调用它的方法时,用接口编程会是什么样子?

    1 回复  |  直到 7 年前
        1
  •  5
  •   VonC    7 年前

    考虑到接口可以存储stuct 指向结构的指针,请确保将applicationcache结构定义为:

    type ApplicationCache struct { 
      Cache ICacheEngine
    }
    

    见“ Cast a struct pointer to interface pointer in Golang “。