You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I would like to suggest a pattern for composable functional options using go generics. This pattern is useful in the case where functional options are reused in several functions/methods, with subtle differences.
In order to make it work in a user-friendly way, inference would need to be modified/augmented for generics.
Rational
When dealing with large libraries, one often reuse functional options that are applicable to several methods/functions.
Unfortunately, the inference system is not capable to infer the type of options to use what makes mandatory to instantiate WithPort using the type MyOption:
Apply(WithPort(15), WithFlag())
returns:
./prog.go:82:16: cannot infer T (prog.go:27:15)
Similarly, the following does not work either:
varoptfunc(MyOption) =WithPort(15)
whereas the following work:
varoptfunc(MyOption) =WithPort[MyOption](15)
Would such a change in the inference be possible?
Thanks, Thomas
The text was updated successfully, but these errors were encountered:
I would like to suggest a pattern for composable functional options using go generics. This pattern is useful in the case where functional options are reused in several functions/methods, with subtle differences.
In order to make it work in a user-friendly way, inference would need to be modified/augmented for generics.
Rational
When dealing with large libraries, one often reuse functional options that are applicable to several methods/functions.
This generates a lot of boilerplate code as one method needs to be added for each and everyone of the option structs.
An example of this pattern (taken from https://sagikazarmark.hu/blog/functional-options-on-steroids/):
A larger version of such a pattern: https://github.com/airbusgeo/godal/blob/main/options.go
Proposal
Use generics to create composable options and decrease boiler plate code.
Complete version in playground: https://go.dev/play/p/HS_CIFTUtqk?v=gotip
Unfortunately, the inference system is not capable to infer the type of options to use what makes mandatory to instantiate
WithPort
using the typeMyOption
:returns:
Similarly, the following does not work either:
whereas the following work:
Would such a change in the inference be possible?
Thanks, Thomas
The text was updated successfully, but these errors were encountered: