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条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致