shearn89
shearn89

Reputation: 887

Golang interfaces and receivers - advice needed

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!

Upvotes: 2

Views: 821

Answers (1)

icza
icza

Reputation: 417462

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)
}

Upvotes: 3

Related Questions