【发布时间】:2016-09-20 12:33:11
【问题描述】:
我想优化我的代码,然后我有以下情况:
我有一个通用的struct,其中只有一个字段给出了规范,比如说一个缓存结构示例:
# 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
}
我当前的解决方案遵循之前的定义,并为每个元素创建一个缓存(必须如此:每个元素一个缓存):
var cache_for_element_A Cache{}
var cache_for_element_B Cache{}
但是通过这种方式,我必须在阅读时始终转换memory_cache,即使我已经知道内容是什么(那么就不需要转换大小写了)。
下面的代码做了我想要的,但它定义了两倍的冗余/公共字段,因此我想找到另一个解决方案。
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
}
那么,是否可以在结构中定义一个字段(更准确地说是Cache.memory_cache),当声明发生时可以进一步定义,而不使用interface?
【问题讨论】: