It could be a beginner's question. Code is like,
type MYMAP map[int]int
func (o *MYMAP) dosth(){
//this will fail to compile
o[1]=2
}
error message: invalid operation: o[1] (index of type *MYMAP)
How to access the underlying type of MYMAP as map?
Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.
You can iterate through a map in Golang using the for... range statement where it fetches the index and its corresponding value. In the code above, we defined a map storing the details of a bookstore with type string as its key and type int as its value. We then looped through its keys and values using the for..
You can retrieve the value assigned to a key in a map using the syntax m[key] . If the key exists in the map, you'll get the assigned value. Otherwise, you'll get the zero value of the map's value type.
Go's map is a hashmap. The specific map implementation I'm going to talk about is the hashmap, because this is the implementation that the Go runtime uses.
The problem isn't that it's an alias, it's that it's a pointer to a map.
Go will not automatically deference pointers for map or slice access the way it will for method calls. Replacing o[1]=2
with (*o)[1]=2
will work. Though you should consider why you're (effectively) using a pointer to a map. There can be good reasons to do this, but usually you don't need a pointer to a map since maps are "reference types", meaning that you don't need a pointer to them to see the side effects of mutating them across the program.
An easy fix could be done by getting rid of pointer, just change o *MYMAP
to o MYMAP
type MYMAP map[int]int
func (o MYMAP) dosth(){
o[1]=2
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With