Accessing a map using its reference

前端 未结 3 1133
悲&欢浪女
悲&欢浪女 2021-02-01 05:53

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(sessio         


        
相关标签:
3条回答
  • 2021-02-01 06:03

    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

    0 讨论(0)
  • 2021-02-01 06:05

    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.

    0 讨论(0)
  • 2021-02-01 06: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.

    0 讨论(0)
提交回复
热议问题