我正在嘗試將 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 中這是個好主意嗎?替代的圍棋主義是什么?
1 回答

手掌心
TA貢獻1942條經驗 獲得超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)
}
- 1 回答
- 0 關注
- 210 瀏覽
添加回答
舉報
0/150
提交
取消