Golang - 将 "inheritance"添加到结构中

标签 go struct interface

我想优化我的代码,然后出现以下情况:

我有一个通用的结构,其中只有一个字段给出规范,比方说一个缓存结构示例:

# 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 (那么就不需要强制转换)。


下面的代码做了我想要的事情,但它定义了两倍的冗余/公共(public)字段,因此我想找到另一个解决方案。

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)

最佳答案

Go 没有泛型,因此没有简单的方法可以做到这一点,例如在 Java 中 ( class Cache<T>().... )。

您可以做的一件事是用一个小型类型化函数包装您的缓存,该函数仅从通用缓存中获取对象并将接口(interface)转换为正确的类型。这只会让您免于在代码中一遍又一遍地编写接口(interface)转换。

type ElemACache struct { 
   Cache
}

func (c *ElemeACache)Get(key string) ElemeA {
    return c.Cache.Get(key).(ElemeA) //of course add checks here
}

关于Golang - 将 "inheritance"添加到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39594229/

相关文章:

go - openpgp 和 golang

pointers - 如何更改在golang中作为结构引用传递的空接口(interface)的值?

C# 语言设计 : explicit interface implementation of an event

java - 在父类(super class)中使用子类的方法

go - go 二进制文件是否可以重新加载自身?

go - 将任意JSON发送到 gorilla websocket连接

c - 访问结构体内部的数组

java - 获取由 JNA 中的参数返回的不透明结构

java - 类引用和接口(interface)引用之间的区别

interface - Go 和 interface{} 相等