Compilation Issue when passing map[string]struct{}

101 views
Skip to first unread message

Pranay Agarwal

unread,
May 25, 2023, 8:36:04 AM5/25/23
to golang-nuts
Hello,

I am using Go 1.20.4 on Ubuntu 22.04. I am facing a compilation error when I attempt to pass a map from a string to a struct to a function that expects a map from string to an interface.

Here is some example code demonstrating the issue: https://goplay.tools/snippet/GrPfTWfycdx

Here, the struct is Helper, and it conforms to both interface definitions - Helper1 and Helper2. I am able to pass in an instance of Helper directly, however when I attempt to pass a map[string]Helper the compiler throws a type error IncompatibleAssign.

I was wondering if anyone else has faced something similar? And if so, how did you solve this issue. Would appreciate any input, thank you.

Regards,
Pranay Agarwal

Ian Lance Taylor

unread,
May 25, 2023, 2:14:03 PM5/25/23
to Pranay Agarwal, golang-nuts
Go doesn't work that way. You can't freely interchange a type with an
interface type, even if the type implements the interface. For a
related scenario, see https://go.dev/doc/faq#covariant_types. The
only fix is to be consistent: if you need a map to an interface, build
a map to an interface type. If you need to support two different
interfaces, build a map to any, and use a type assertion.

Ian
Reply all
Reply to author
Forward
0 new messages