douershuang7356 2015-04-07 09:56
浏览 55
已采纳

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

I'm trying to convert my config loader class in Golang from a specific config file structure to a more general one. Originally, I defined a struct with a set of program-specific variables, for example:

type WatcherConfig struct {
    FileType   string
    Flag       bool
    OtherType  string
    ConfigPath string
}

I then defined two methods with pointer receivers:

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

and

func (config *WatcherConfig) Reload() error {}

I'm now attempting to make this more general, and the plan was to define an interface Config and define the LoadConfig and Reload methods on this. I could then create a struct with the config layout for each module that needed it, and save myself repeating a method that basically opens a file, reads JSON, and dumps it into a struct.

I've tried creating an interface and defining a method like this:

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

But that is obviously throwing errors as Config is not a type, it's an interface. Do I need to add a more abstract struct to my class? It may be useful to know that all configuration structs will have the ConfigPath field, as I use this to Reload() the config.

I'm fairly sure I'm going about this the wrong way, or what I'm trying to do isn't a pattern that works nicely in Go. I'd really appreciate some advice!

  • Is what I'm trying to do possible in Go?
  • Is it a good idea in Go?
  • What would be the alternative Go-ism?
  • 写回答

1条回答 默认 最新

  • duanlinma5885 2015-04-07 10:13
    关注

    Even if you'd use embedding both the interfaces and the implementations, the implementation of Config.LoadConfig() cannot know about the type that embeds it (e.g. WatcherConfig).

    Best would be not to implement this as methods but as simple helper or factory functions.

    You could do it like this:

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看