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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?