Re:Reusable and type-safe options for Go APIs
by tomjakubowski on Sunday October 22, 2017 @07:24AM
(#15526241)
The zero value problem would be a non-issue if Go had a built-in ?T type ("option T").
Re:Reusable and type-safe options for Go APIs
by ctz on Sunday October 22, 2017 @08:12AM
(#15526453)
That's problematic, thanks to golang choosing to have always-nullable reference types. "option T*" would therefore be a tristate type, unless it was somehow specialised into representing nullability (obviously a major breaking change).
Re:Reusable and type-safe options for Go APIs
by weberc2 on Sunday October 22, 2017 @08:19AM
(#15526482)
If mostly everyone uses Option instead of `nil`, the problem approaches a vanishing point. Not perfect, but still a massive improvement. Of course, generics won't be added until Go 2 anyway, at which point the community is free to make a breaking change, though I doubt they'll ditch `nil`.
Re:Reusable and type-safe options for Go APIs
by everdev on Sunday October 22, 2017 @01:07PM
(#15527762)
For the zero value problem, a pointer is usually used rather than an "identifier value" like -1.
var price *float64
if price == nil {
// Handle empty value
}
Re:Reusable and type-safe options for Go APIs
by sfifs on Sunday October 22, 2017 @08:26PM
(#15529832)
This works if you can guarantee the variable will not ever change after being set which is not unreasonable for configuration options.
However if you are dealing with variables that can mutate in a concurrent environment, you might have a race condition if you pass by pointer reference rather than by value
Rob doesn't explain why a config struct is not good for him in his reference article, and Dave is saying that's because 1/ it needs to be passed even when it's empty and 2/ its zero values may be a trouble, giving the example of explicitly setting `Port` to 0 to let OS selecting first free port available.
I would say that I have absolutely no problem with passing an empty option struct : that's simple. I know what is going on, I don't have to check sources for three methods to understand it.
Regarding the zero value problem, the example of port selection seems incredibly an edge case. Most of the time, if some option is numeric and can have a special feature, -1 will be used rather than 0 (like it's often the case when passing a limit to specify "no limit"). For the port problem, I would have no problem passing an `AutoselectFreePort bool` option.
But then again, maybe the pattern seems complicated to me because it's new. We'll see with time.