Interface Golang接口和接收器-需要建议

Interface Golang接口和接收器-需要建议,interface,go,abstraction,Interface,Go,Abstraction,我正在尝试将Golang中的config loader类从特定的配置文件结构转换为更通用的配置文件结构。最初,我使用一组特定于程序的变量定义了一个结构,例如: type WatcherConfig struct { FileType string Flag bool OtherType string ConfigPath string } 然后,我使用指针接收器定义了两个方法: func (config *WatcherConfig) Load

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

type WatcherConfig struct {
    FileType   string
    Flag       bool
    OtherType  string
    ConfigPath string
}
然后,我使用指针接收器定义了两个方法:

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

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

我尝试过创建一个接口并定义如下方法:

type Config interface {
    LoadConfig(string) error
}
func (config *Config) LoadConfig(path string) error {}
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
不是一种类型,而是一个接口。我需要向类中添加更抽象的
结构吗知道所有配置结构都将具有
ConfigPath
字段可能很有用,因为我使用它来
Reload()
配置

我相当肯定我是走错了路,或者我尝试做的不是一个在围棋中运行良好的模式。我真的很感谢你的建议

  • 在围棋中我想做的事可能吗
  • 围棋是个好主意吗
  • 另一种选择是什么
即使您同时使用嵌入接口和实现,
Config.LoadConfig()
的实现也无法知道嵌入它的类型(例如
WatcherConfig

最好不要将其作为方法实现,而是作为简单的助手或工厂函数实现

你可以这样做:

type Config interface {
    LoadConfig(string) error
}
func (config *Config) LoadConfig(path string) error {}
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)
}

当您可以创建func LoadConfig(路径字符串)(Config,error){}时,为什么要定义一个方法呢?啊,这很有道理!我没有想到使用
config.Path()
方法来确保config对象具有路径字符串。不错!