Go 1.18: reflect implicit type conversion

230 views
Skip to first unread message

Dave Keck

unread,
Apr 15, 2022, 9:33:39 PM4/15/22
to golan...@googlegroups.com
Hi all,

In this code, the SetMapIndex line panics in Go <1.18, but it no longer panics in Go 1.18:

    type CustomString string
    m := reflect.ValueOf(map[CustomString]int{})
    m.SetMapIndex(reflect.ValueOf("key"), reflect.ValueOf(0))

The panic ("value of type string is not assignable to type CustomString") appears to be prevented in Go 1.18 because reflect implicitly converts string -> CustomString, which Go <1.18 doesn't do.

I had 2 questions:

    - Is it possible to get this implicit conversion behavior in earlier versions of Go? Specifically, I'm using Go 1.16 + the firestore package, and I'd like to use custom string types as map keys.
   
    - Is this change discussed anywhere?
   
Thanks!

David

Dan Kortschak

unread,
Apr 16, 2022, 5:09:37 AM4/16/22
to golan...@googlegroups.com
This is not mentioned in the release notes. I think it is a bug in
1.18; he docs still say that "As in Go, key's elem must be assignable
to the map's key type". This is not the case here.

Bisected to 23832ba2e2fb396cda1dacf3e8afcb38ec36dcba which touches
this.

Dan


Ian Lance Taylor

unread,
Apr 16, 2022, 9:04:33 PM4/16/22
to Dan Kortschak, golan...@googlegroups.com
On Sat, Apr 16, 2022 at 2:09 AM 'Dan Kortschak' via golang-nuts
<golan...@googlegroups.com> wrote:
>
> This is not mentioned in the release notes. I think it is a bug in
> 1.18; he docs still say that "As in Go, key's elem must be assignable
> to the map's key type". This is not the case here.
>
> Bisected to 23832ba2e2fb396cda1dacf3e8afcb38ec36dcba which touches
> this.

For the record, Dan filed https://go.dev/issue/52379 to get this fixed
in 1.19 and 1.18.2 Thanks!

Ian
Reply all
Reply to author
Forward
0 new messages