高隆:使用其参考访问地图 [英] Golang: Accessing a map using its reference
问题描述
func refreshSession(sessions * map [string] Session){
now:= time。现在()
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不支持索引)
我尝试了方括号,但没有影响。如果我拿走所有引用操作符(*&),那么它编译得很好。
我该怎么写?
需要使用带有地图的指针。
地图类型是引用类型,如指针或切片[1]
如果您需要更改会话
,则可以使用指针:
map [string] * Session
[1] https://blog.golang.org/go-maps-inaction
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?
You don't need to use a pointer with a map.
Map types are reference types, like pointers or slices[1]
If you needed to change the Session
you could use a pointer:
map[string]*Session
[1]https://blog.golang.org/go-maps-in-action
这篇关于高隆:使用其参考访问地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!