【问题标题】:Golang interfaces and receivers - advice neededGolang 接口和接收器 - 需要建议
【发布时间】:2015-06-11 21:11:44
【问题描述】:

我正在尝试将我在 Golang 中的配置加载器类从特定的配置文件结构转换为更通用的结构。最初,我定义了一个带有一组程序特定变量的结构,例如:

type WatcherConfig struct {
    FileType   string
    Flag       bool
    OtherType  string
    ConfigPath string
}

然后我用指针接收器定义了两个方法:

func (config *WatcherConfig) LoadConfig(path string) error {}

func (config *WatcherConfig) Reload() error {}

我现在正试图使其更通用,计划是定义一个接口Config 并在此定义LoadConfigReload 方法。然后,我可以为每个需要它的模块创建一个带有配置布局的struct,并省去重复一个基本上打开文件、读取 JSON 并将其转储到结构中的方法。

我尝试过创建一个接口并定义这样的方法:

type Config interface {
    LoadConfig(string) error
}
func (config *Config) LoadConfig(path string) error {}

但这显然会引发错误,因为Config 不是类型,而是接口。我需要在课堂上添加更抽象的struct 吗? 知道所有配置结构都将具有ConfigPath 字段可能很有用,因为我将其用于Reload() 配置。

我很确定我的做法是错误的,或者我正在尝试做的不是一个在 Go 中运行良好的模式。我真的很感激一些建议!

  • 我在 Go 中尝试做的事情是否可行?
  • 在 Go 中这是个好主意吗?
  • 另一种围棋主义是什么?

【问题讨论】:

  • 既然可以创建func LoadConfig(path string) (Config, error){},为什么还要定义方法?

标签: interface go abstraction


【解决方案1】:

即使您同时嵌入接口和实现,Config.LoadConfig() 的实现也无法知道嵌入它的类型(例如WatcherConfig)。

最好不要将其实现为 methods,而是实现为简单的 helperfactory 函数。

你可以这样做:

func LoadConfig(path string, config interface{}) error {
    // Load implementation
    // For example you can unmarshal file content into the config variable (if pointer)
}

func ReloadConfig(config Config) error {
    // Reload implementation
    path := config.Path() // Config interface may have a Path() method
    // for example you can unmarshal file content into the config variable (if pointer)
}

【讨论】:

  • 啊,有道理!我错过了 config.Path() 方法的想法,以确保配置对象具有路径字符串。不错!
猜你喜欢
  • 1970-01-01
  • 2011-12-11
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 2021-08-30
  • 2018-01-20
  • 1970-01-01
相关资源
最近更新 更多