英文:
Accessing a map using its reference
问题
我尝试循环遍历一个作为指针传递给函数的映射,但我找不到访问元素的方法。以下是代码:
func refreshSession(sessions *map[string]Session) {
now := time.Now()
for sid := range *sessions {
if now.After((*sessions)[sid].timestamp.Add(sessionRefresh)) {
delete(*sessions, sid)
}
}
}
在这个例子中,第4行返回以下编译错误:
./controller.go:120: invalid operation: sessions[sid] (type *map[string]Session does not support indexing)
我尝试使用方括号,但没有效果。如果我去掉所有的引用操作符(* &),那么它可以编译通过。
我应该如何编写这段代码?
英文:
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?
答案1
得分: 53
你不需要在map中使用指针。
如果你需要更改Session
,你可以使用指针:
map[string]*Session
英文:
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
答案2
得分: 18
首先取消引用地图,然后访问它(在play上的示例):
(*sessions)[sid]
值得注意的是,地图实际上是引用类型,因此使用指针的用例非常有限。只是将地图值传递给函数不会复制内容。在play上的示例。
英文:
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.
答案3
得分: 11
你没有考虑到 *
的优先级。
*session[sid]
实际上表示 *(session[sid])
,也就是先对指向映射的指针进行索引(因此出现错误),然后再对其进行解引用。
你应该使用 (*session)[sid].timestamp
,先对指向映射的指针进行解引用,然后再使用键访问它。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论