Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use pointers as map keys in Go?

Suppose we add a value to a map using a pointer as the key. Could the memory address of this pointer ever change? If so, will looking it up in the map fail because when it was inserted, it had a different memory address?

like image 357
skoush Avatar asked Jan 04 '16 05:01

skoush


People also ask

Can pointer be a key for map Golang?

A mistake that is easy to make with Go maps is unintentional use of pointers as map keys. For example, consider a map originally keyed on strings. Requirements change and it must now use a combination of two strings as the key.

What can be a key in Golang map?

In the maps, a key must be unique and always in the type which is comparable using == operator or the type which support != operator. So, most of the built-in type can be used as a key like an int, float64, rune, string, comparable array and structure, pointer, etc.

How are maps stored Go?

Save offline maps on an SD cardOffline maps are downloaded on your device's internal storage by default, but you can download them on an SD card instead. If your device is on Android 6.0 or higher, you can only save an area to an SD card that's configured for portable storage.

How do I change the map key in Golang?

To update value for a key in Map in Go language, assign the new value to map[key] using assignment operator. If the key we are updating is already present, then the corresponding value is updated with the new value.


1 Answers

Could the memory address change, in the pointers-as-uints sense? Yes, but outside of the unsafe package go doesn't expose pointers as uints. So, will looking it up in the map fail? No.

See more at the spec. The linked section even includes a pointer-keyed map as an example.

like image 151
W. Cybriwsky Avatar answered Nov 02 '22 04:11

W. Cybriwsky