2015-04-07 37 views
2

我想將我在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並且在這個上定義LoadConfigReload方法。然後,我可以爲每個需要它的模塊創建一個struct,並保存自己重複一個基本上打開文件,讀取JSON並將其轉儲到結構中的方法。

我試圖創建一個接口,定義這樣的方法:

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

但是,這顯然是引發錯誤的Config不是一個類型,它是一個接口。我需要爲我的班級添加更抽象的struct嗎? 知道所有配置結構將具有ConfigPath字段可能會有用,因爲我將此用於Reload()配置。

我很確定我正在討論這個錯誤的方法,或者我正在嘗試做的不是一個在Go中很好地工作的模式。我真的很感激一些建議!

  • 我想在Go中做什麼?
  • Go是一個好主意嗎?
  • 什麼是替代Go-ism?
+0

爲什麼定義的時候你可以創建FUNC LoadConfig(路徑字符串)(配置,錯誤){}的方法? – Makpoc

回答

3

即使你使用嵌入兩個接口和實施中,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) 
} 
+0

啊,這很有道理!我錯過了'config.Path()'方法的想法,以確保配置對象有一個路徑字符串。好一個! – shearn89