On Wed, Aug 31, 2022 at 7:28 AM antonio.o...@gmail.com < antonio.ojea.gar...@gmail.com> wrote:
> Hi, > > Based on the documentation: > > "The map key can be any type that is comparable." > "Struct values are comparable if all their fields are comparable. Two > struct values are equal if their corresponding non-blank fields are equal." > "Interface values are comparable. Two interface values are equal if they > have identical dynamic types and equal dynamic values or if both have value > nil." > > My understanding is that I can use an structure like this as a key for a > map > > type dialer interface { > dial() > } > > type key struct { > id string > number int > dialer dialer > } > > It also seems to work fine https://go.dev/play/p/hKQfx-JH5WP > This works in general, but your example is flawed. In your example, you have f1 := &fakedialer{} f2 := &fakedialer2{} and then use f1 anf f2 as keys. These are pointers to structs, so the comparison will be pointer comparison, not field-by-field comparison. If you do: f1 := fakedialer{} f2 := fakedialer2{} and replace the pointer receivers with value receivers, and then use these as map keys, it will work. But this time, if you pass a struct that cannot be used as a key, you'll receive a runtime panic instead of a compile error. > But I'm wondering if I'm missing something or are there some corner cases > I should take into account before doing this ... or if this is not > recommended at all > > Thanks, > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/97b7368e-d276-40ab-afa3-f8a7868fd9ean%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/97b7368e-d276-40ab-afa3-f8a7868fd9ean%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAMV2Rqq4qLv6eaBcRJ7r%3DOn3D%2B9YxLeaVSnfme-F187md%3DR7LA%40mail.gmail.com.