27

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?

0

3 Answers 3

55

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

Sign up to request clarification or add additional context in comments.

6 Comments

question, would there be cases where its plausible to have a map's key to be pointer of x type?
Do you mean something like map[*T]string?
Is something like map[*T]string possible?
@harunrashid indeed, check out this example play.golang.com/p/GlEzMDDZdPa
map[string]*Session will not modify the map globally, as original code does
|
18

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.

Comments

11

You are not taking into account the precedence of *.

*session[sid] really means *(session[sid]), that is, first indexing the pointer to map (hence the error), then dereferencing it.

You should use (*session)[sid].timestamp to first dereference the pointer to the map and then access it using the key.

2 Comments

I find this very rare. I tried it and it works: play.golang.org/p/85Mj8RixGm . If @jmaloney solutions works for you, are you sure you are using the same code you posted here?
I had other issues in the code. So it changed. I updated it in the question above. But the problem I had first went away after I got rid of all * and &.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.