高隆:使用其参考访问地图 [英] Golang: Accessing a map using its reference

查看:97
本文介绍了高隆:使用其参考访问地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图循环遍历一个地图,我传递一个指针到一个函数,但我找不到一种访问元素的方式。这是代码:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆