duanjiao4763 2016-09-20 12:33
浏览 57
已采纳

Golang-在结构中添加“继承”

I would like to optimize my code, I have then the following situation:

I have a general struct where only one field gives the specification, let say a cache struct example:

# the main cache struct
type Cache struct {
  name             string
  memory_cache     map[string]interface{}
  mutex            *sync.Mutex
  ...              ...
  # common fields
}

# an element stored in the Cache.memory_cache map
type ElementA {
  name  string
  count int64
}

# an element stored in the Cache.memory_cache map
type ElementB {
  name  string
  tags  []string
}

My current solution follow the previously definition and I create a cache for each element (it must be so: one cache per element):

var cache_for_element_A Cache{}
var cache_for_element_B Cache{}

But in this way I must always cast the memory_cache when reading, even if I know already what is the content (then no cast-case should be needed).


The following code do what I would like to have, but it defines twice a lot of redundants/commons fields, for this reason I would like to find another solution.

type CacheForA struct {
  name             string
  memory_cache     map[string]ElementA{}
  mutex            *sync.Mutex
  ...              ...
  # common fields
}

type CacheForB struct {
  name             string
  memory_cache     map[string]ElementB{}
  mutex            *sync.Mutex
  ...              ...
  # common fields
}

Then, is it possible to define a field in the struct (more precisely Cache.memory_cache) that can be further defined when the declaration occurs and without using interface?

  • 写回答

2条回答 默认 最新

  • drxd54816 2016-09-20 12:46
    关注

    Go doesn't have generics, so there's no simple way of doing this, like you would in Java for instance (class Cache<T>()....).

    One thing you can do is wrap your cache with a small typed function that just fetches objects from a generic cache and converts the interface to the right type. This just saves you from writing the interface conversion over and over in your code.

    type ElemACache struct { 
       Cache
    }
    
    func (c *ElemeACache)Get(key string) ElemeA {
        return c.Cache.Get(key).(ElemeA) //of course add checks here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程