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

我正在尝试将 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 中这是个好主意吗?

  • 替代的围棋主义是什么?


噜噜哒
浏览 188回答 1
1回答

手掌心

即使您同时使用嵌入接口和实现, 的实现Config.LoadConfig()也无法知道嵌入它的类型(例如WatcherConfig)。最好不要将其实现为方法,而是实现为简单的帮助程序或工厂函数。你可以这样做: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)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go