SetMapIndex() equivalent for slice/array

104 views
Skip to first unread message

Deiter

unread,
Jun 4, 2021, 11:29:28 PM6/4/21
to golang-nuts

The reflect package provides the SetMapIndex method for updating elements in a map that are represented by a reflect.Value type, but I don’t see an equivalent for array/slice.

The sample app (link provided below) includes an example of map that’s been made accessible through a a reflect.Value type variable. One of the elements in the map is updated using SetMapIndex.

The sample app also includes an example of a slice containing exactly the same data as the map. As far as I can tell, the only way to update an element of the slice through a reflect.Value type variable is to introduce unsafe package

Is there a better way that I’m missing that doesn’t require the use of the unsafe package

SetMapIndex() equivalent for slice/array

Kurtis Rader

unread,
Jun 4, 2021, 11:45:08 PM6/4/21
to Deiter, golang-nuts
More context would be useful; i.e., what are you really trying to do and why? Such information often allows people to provide better answers; including whether this is an example of the [XY Problem](https://xyproblem.info/) or you have a misunderstanding how slices work. Given your play.golang.org reproducer neither of those responsies seem likely but nonetheless...

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e292b828-4ba9-420d-af2d-8c98fc451ef9n%40googlegroups.com.


--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

Howard Waterfall

unread,
Jun 5, 2021, 12:09:36 AM6/5/21
to Kurtis Rader, golang-nuts
I'm trying to decouple algorithm from type. if an algorithm works on a collection, it ought to work on either a map or slice. It appeared that result.Value facilitated the decoupling entirely, until I ran into the limitation with array/slice. It seems odd that I have to use the unsafe the package with array/slice esp. given the support provided for maps with SetMapIndex. I figure I must be missing something…

Dan Kortschak

unread,
Jun 5, 2021, 12:10:53 AM6/5/21
to Deiter, golang-nuts
You can call Set on the reflect.Value returned by Index of a slice or
array.

slice: https://play.golang.org/p/b1NscgQ7UC5
array: https://play.golang.org/p/xCAGuTL5Wbl


Howard Waterfall

unread,
Jun 5, 2021, 9:28:00 AM6/5/21
to Dan Kortschak, golang-nuts
Dammit!. How'd I miss that?! Thanks Dan. I updated the sample accordingly.

Howard Waterfall

unread,
Jun 5, 2021, 10:59:13 AM6/5/21
to Dan Kortschak, golang-nuts
Reply all
Reply to author
Forward
0 new messages