Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a map using its reference

Tags:

I try to loop through a map, that I pass as a pointer to a function, but I can't find a way to access the elements. This is the code:

func refreshSession(sessions *map[string]Session) {     now := time.Now()     for sid := range *sessions {         if now.After(*sessions[sid].timestamp.Add(sessionRefresh)) {             delete( *sessions, sid )         }     } } 

Line 4 in this example return following compile error:

./controller.go:120: invalid operation: sessions[sid] (type *map[string]Session does not support indexing) 

I tried brackets, but it had no effect. If I take away all reference operators (* &) then it compiles fine.

How must I write this?

like image 515
Michael Avatar asked Feb 07 '15 16:02

Michael


People also ask

How do you pass a map by reference in Go?

If you assign to a map value, you will break its relationship with other variables. Go has no reference types, everything is a value. You can demonstrate this with func mapToAnotherFunction(m map[string]int) { m = nil } , it doesn't empty the map, just overwrites its value in a local way.

Are maps pointers?

Maps, like channels, but unlike slices, are just pointers to runtime types. As you saw above, a map is just a pointer to a runtime.

What does map return if key doesnt exist?

If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.


2 Answers

You don't need to use a pointer with a map.

Map types are reference types, like pointers or slices

If you needed to change the Session you could use a pointer:

map[string]*Session

like image 53
jmaloney Avatar answered Sep 23 '22 10:09

jmaloney


De-reference the map first and then access it (Example on play):

(*sessions)[sid] 

It's also noteworthy that maps are actually reference types and therefore there is a very limited use-case of using pointers. Just passing a map value to a function will not copy the content. Example on play.

like image 45
nemo Avatar answered Sep 22 '22 10:09

nemo