Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of using derived map type index in golang

Tags:

go

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?

like image 964
Jason Xu Avatar asked Apr 22 '14 05:04

Jason Xu


People also ask

How is map implemented in Golang?

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.

How do I iterate through a map in Golang?

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..

How do I read a map in Golang?

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.

Is Golang map a hash map?

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.


2 Answers

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.

like image 162
Linear Avatar answered Oct 04 '22 19:10

Linear


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
}
like image 42
Muhammad Soliman Avatar answered Oct 04 '22 21:10

Muhammad Soliman