by majewsky · 7y ago · 0 comments
What I like to do is to make the last arg take a struct such that you indirectly have named (and optional) arguments:
type DownloadOpts struct {
UserAgent string
TimeoutSeconds int
//...
}
func Download(url string, opts DownloadOpts) (io.Reader, error) {
...
}
//use like:
contents, err := Download("https://news.ycombinator.com", DownloadOpts {
UserAgent: "example-snippet/1.0",
})
> Never needing to pause for garbage collection could also be a factor [in Rust's greater speed compared to Go].Would be nice if the author had checked
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
print(ms.NumGC)
to see if there was actually any garbage collection performed.Rob Pike, and Dave Cheney both posted about this [1][2]. They summarised that using self-referential functions were a more optimal way for handling options to a function. This gives the benefit of allowing the options to be easily extensible by yourself, and any users that would be interacting with your API.
[1] - https://commandcenter.blogspot.com/2014/01/self-referential-...
[2] - https://dave.cheney.net/2014/10/17/functional-options-for-fr...