【发布时间】: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 并在此定义LoadConfig 和Reload 方法。然后,我可以为每个需要它的模块创建一个带有配置布局的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