inconsistent type alias conversion

55 views
Skip to first unread message

adrien...@swisstopo.ch

unread,
Dec 17, 2025, 12:52:12 PM (yesterday) Dec 17
to golan...@googlegroups.com
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

Jason E. Aten

unread,
Dec 17, 2025, 1:41:32 PM (yesterday) Dec 17
to golang-nuts
Let's get the terminology correct, since it seems you have the definitions
wrong in your question, and that may be a source of confusion when you are reading the
rules for "type definition" versus "type alias":

"type LoadOptionsFunc = func(*LoadOptions) error" is a type alias.

"type LoadOptionsFunc func(*LoadOptions) error" is a type definition.


So if you do actually use a type alias, your program will work.

https://go.dev/play/p/nFW_avNXT4R
Reply all
Reply to author
Forward
0 new messages