Greetings golang-nuts,
Consider the following API:
type Config struct{}
type LoadOptions struct{}
type LoadOptionsFunc func(*LoadOptions) error
func Loader(optFns ...func(*LoadOptions) error) (Config, error)
I am trying to add my own loader on top of it like this:
func myLoader(optFns ...LoadOptionsFunc) (Config, error) {
// Do some stuff here.
return Loader(optFns...)
}
This fails at compilation time like this:
./prog.go:22:16: cannot use optFns (variable of type []LoadOptionsFunc) as []func(*LoadOptions) error value in argument to Loader
Go Playground link (a):
https://go.dev/play/p/0Z3wGF5iq5m
If I change the API to use the LoadOptionsFunc alias, it works:
func Loader(optFns ...LoadOptionsFunc) (Config, error)
Go Playground link (b):
https://go.dev/play/p/p_aVqfACgsR
If I change myLoader to explicitly copy the arguments to be of the underlying type, it works:
func myLoader(optFns ...LoadOptionsFunc) (Config, error) {
loadOptions := []func(*LoadOptions) error{}
for _, o := range optFns {
loadOptions = append(loadOptions, o)
}
// Do some stuff here.
return Loader(loadOptions...)
}
Go Playground link (c):
https://go.dev/play/p/yv3VAkaTsFI
If I change the type to be an alias to int, that workaround fails.
Go Playground link (d):
https://go.dev/play/p/hSB2528bMMH
Unless I explicitly coerce the type of each element with int().
Go Playground link (e):
https://go.dev/play/p/nWdRUGH2o0q
Is this really working as intended? Given I cannot change the API to make Loader use the type alias, is my workaround from (c) the correct way to resolve this? Why does it work differently if the alias points to a func or an int?
Verified with Go 1.24.2 and 1.25 (from the Playground) if that matters.
Thanks,
Adrien Kunysz