Original post

I’ve noticed a theme in some projects I’ve been looking at recently, such as Viper and Req. They both have imported methods which act on a globally-defined instance of some struct in order to make the package easier to use.

For example, while using req, you can do:

req.Get(url) 

Or, you can do the slightly more verbose

r := req.New() r.Get(url) 

Viper is the same. It’s a tool for easily getting program configuration by looking at config files and environment variables. Again, you can either do

viper.SetDefault(...) 

Or

v := viper.New() v.SetDefault(...) 

In the source code for the packages, this leads to a lot of repetition:

var v *Viper func init() { v = New() } // ..... func SetConfigFile(in string) { v.SetConfigFile(in) } func (v *Viper) SetConfigFile(in string) { if in != "" { v.configFile = in } } 

As each method needs to be defined on both the globally and also as a method of v.

My question is if there is a tool, like Stringer, which can automatically create all of these global definitions for you? Something like “globalify” which would create a new file with all of a struct’s methods as global definitions. Also, is this style of idiomatic ?

I tried googling, but didn’t get any results. Thanks for any help in advance.

submitted by /u/ollybritton
[link] [comments]