Python kwargs and Beyond in Golang
Python kwargs and Beyond in Golang - Soheil HassasYeganeh - Medium
While working on Beehive’s API, I observed a pattern similar to @davecheney’s functional options: We have lots of configuration options that their values can be (a) set by the user, (b) overridden through command-line flags, or (c) set using a default constant value.In an effort to generalize that, I developed a library called args (https://github.com/soheilhy/args). Here is an example:Server() has three optional arguments: ListenOn, BufferSize, and StateDir. ListenOn, BufferSize, and StateDir are all optional arguments. ListenOn is an int argument, BufferSize a Uint64, and StateDir a string. The default values of ListenOn and BufferSize are respectively 8080 and 1024*1024. StateDir’s default value is “/tmp” which can be also overridden by the -test.state.dir command-line flag.The end-result is very similar to Python’s kwargs: Instead of writing Server(listen_on=80), we write Server(ListenOn(80)). Although you cannot pass an arbitrary parameter name as in Python, args is safer and, in my very biased opinion, looks a little bit more elegant.Sometimes, you would prefer a typed list arguments instead of the generic args.V. That requires a few more lines of boilerplates wrapping the generic arguments: